<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Web Solutions
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: mslaria $ ($Date: 2007/07/25 14:20:42 $)
// $RCSfile: functions_ticketmain.php,v $ : $Revision: 1.83 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================

if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

require_once ("./modules/tickets/functions_alertrules.php");

define("SUBJECT_USER", 1);
define("SUBJECT_ALERT", 2);
define("SUBJECT_THIRDPARTY", 3);

/**
* Main Ticket Management Class
*/
class TicketMain
{
	var $ticketid = 0;
	var $ticket;
	var $ticketcache = array();
	var $replycache = array();
	var $alerts;
	var $updatesql = array();
	var $auditsql = array();
	var $recount = array();
	var $logtype = LOG_SYSTEM;
	var $norecount = false;
	var $noalertrules = false;
	var $messageid;
	var $duetimecleared = false;
	var $resetsla = false;
	var $_parseremail = array();

	/**
	* Main Constructor
	*/
	function TicketMain($ticketid, $checkdepartment = false, $logtype = false)
	{
		global $_SWIFT;

		$this->ticket = $this->getTicket($ticketid);
		$this->ticketid = $this->ticket["ticketid"];
		if (!$this->ticket)
		{
			return false;
		}

		$this->ticket["labels"] = array();

		if ($checkdepartment == true)
		{
			$_assigns = getAssignedDepartments(MODULE_TICKETS);

			if (!in_array($this->ticket["departmentid"], $_assigns))
			{
				unset($this->ticket);
				unset($this->ticketid);
				return false;
			}
			$this->logtype = LOG_STAFF;
		}
		if ($logtype)
		{
			$this->logtype = $logtype;
		}

		$this->ticket["fticketid"] = iif($_SWIFT["settings"]["t_eticketid"]=="seq",$this->ticket["ticketid"], $this->ticket["ticketmaskid"]);

		$this->alerts =& new TicketAlertRules($this);
		register_shutdown_function(array(&$this, "processTicketQueries"));

		return true;
	}

	/**
	* Get the ticket from database and load it in cache
	*/
	function getTicketData($ticketid)
	{
		global $dbCore, $_SWIFT;

		$_ticket = $dbCore->queryFetch("SELECT tickets.*, users.usergroupid AS usergroupid, tl.lockstaffid, tl.lockdateline, users.userpasswordtxt FROM `". TABLE_PREFIX ."tickets` AS tickets LEFT JOIN `". TABLE_PREFIX ."ticketlocks` AS tl ON (tickets.ticketid = tl.ticketid) LEFT JOIN `". TABLE_PREFIX ."users` AS users ON (tickets.userid = users.userid) WHERE tickets.ticketid = '". $dbCore->escape($ticketid) ."';");
		if (!empty($_ticket["ticketid"]))
		{
			$_SWIFT["ticketcache"][$ticketid] = $_ticket;

			return $_SWIFT["ticketcache"][$ticketid];
		} else {
			return false;
		}
	}

	/**
	* Get the ticket from cache, if not set.. return false
	*/
	function getTicketCache($ticketid)
	{
		global $_SWIFT;

		if ($_SWIFT["ticketcache"][$ticketid]["ticketid"] == $ticketid && trim($ticketid) != "")
		{
			return $_SWIFT["ticketcache"][$ticketid];
		} else {
			return false;
		}
	}

	/**
	* Tries to get ticket from cache first, if doesnt exist.. loads the ticket
	*/
	function getTicket($ticketid)
	{
		$_ticketcache = $this->getTicketCache($ticketid);
		if (!$_ticketcache)
		{
			return $this->getTicketData($ticketid);
		} else {
			return $_ticketcache;
		}
	}

	/**
	* Processes Collective Queries at once for a ticket.
	*/
	function processTicketQueries()
	{
		global $_SWIFT, $dbCore;

		if (count($this->updatesql))
		{
			$dbCore->query("UPDATE `". TABLE_PREFIX ."tickets` SET ". implode(",", $this->updatesql) ." WHERE `ticketid` = '". intval($this->ticket["ticketid"]) ."';");
		}

		if (count($this->auditsql))
		{
			$dbCore->query("INSERT INTO `". TABLE_PREFIX ."auditlogs` (`ticketid`, `staffid`, `departmentid`, `userid`, `dateline`, `logtype`, `actiontype`, `actionmsg`) VALUES ". implode(",", $this->auditsql) .";");
		}

		if (count($this->recount) && !$this->norecount)
		{
			require_once (dirname(__FILE__)."/functions_ticketcore.php");
			rebuildTicketCountCache($this->recount);
		}

		if ($this->resetsla == true)
		{
//			echo "Resetting SLA<BR />";
			unset($this->updatesql);
			unset($this->auditsql);
			unset($this->recount);

			$this->resetSLATimeline(false, true);
			$this->resetsla = false;

			$this->processTicketQueries();
		}

		unset($this->updatesql);
		unset($this->auditsql);
		unset($this->recount);
	}

	/**
	* Update given field in ticket
	*/
	function updateField($fieldsql)
	{
		global $_SWIFT;

		if (!$this->ticket)
		{
			return false;
		}

		$this->updatesql[] = $fieldsql;
	}

	/**
	* Get the Return Email address
	*/
	function getReturnEmail($emailqueueid = -1)
	{
		global $_SWIFT;

		if ($emailqueueid == 0 && !empty($_SWIFT["staff"]["staffid"]))
		{
			return $_SWIFT["staff"]["email"];
		} else if ($emailqueueid > 0) {
			if (!empty($_SWIFT["queuecache"]["list"][$emailqueueid]["customfromemail"]))
			{
				return $_SWIFT["queuecache"]["list"][$emailqueueid]["customfromemail"];
			}

			return $_SWIFT["queuecache"]["list"][$emailqueueid]["email"];
		} else if ($emailqueueid == 0 && empty($_SWIFT["staff"]["staffid"])) {
			return $_SWIFT["settings"]["general_returnemail"];
		}

		if (!empty($this->ticket["emailqueueid"]) && isset($_SWIFT["queuecache"]["list"][$this->ticket["emailqueueid"]]))
		{
			if (!empty($_SWIFT["queuecache"]["list"][$this->ticket["emailqueueid"]]["customfromemail"]))
			{
				return $_SWIFT["queuecache"]["list"][$this->ticket["emailqueueid"]]["customfromemail"];
			} else {
				return $_SWIFT["queuecache"]["list"][$this->ticket["emailqueueid"]]["email"];
			}
		} else if (count($_SWIFT["queuecache"]["list"])) {
			// Try to get the queue for the specified department
			foreach ($_SWIFT["queuecache"]["list"] as $key=>$val)
			{
				if ($val["departmentid"] == $this->ticket["departmentid"])
				{
					return iif(!empty($val["customfromemail"]), $val["customfromemail"], $val["email"]);
				}
			}
		}
		return $_SWIFT["settings"]["general_returnemail"];
	}

	/**
	* Get the Return Name
	*/
	function getReturnName($emailqueueid = -1)
	{
		global $_SWIFT;

		if ($emailqueueid == 0 && !empty($_SWIFT["staff"]["staffid"]))
		{
			return $_SWIFT["staff"]["fullname"];
		} else if ($emailqueueid > 0) {
			$_queue = $_SWIFT["queuecache"]["list"][$emailqueueid];
			if (!empty($_queue["emailqueueid"]) && !empty($_queue["customfromname"]))
			{
				return $_queue["customfromname"];
			} else if (!empty($_SWIFT["staff"]["fullname"])) {
				return $_SWIFT["staff"]["fullname"];
			}
		} else if ($emailqueueid == 0 && empty($_SWIFT["staff"]["staffid"])) {
			return $_SWIFT["settings"]["general_companyname"];
		} 

		if (!empty($this->ticket["emailqueueid"]) && isset($_SWIFT["queuecache"]["list"][$this->ticket["emailqueueid"]]))
		{
			if (!empty($_SWIFT["queuecache"]["list"][$this->ticket["emailqueueid"]]["customfromname"]))
			{
				return $_SWIFT["queuecache"]["list"][$this->ticket["emailqueueid"]]["customfromname"];
			} else if (!empty($_SWIFT["staff"]["fullname"])) {
				return $_SWIFT["staff"]["fullname"];
			}
		} else if (count($_SWIFT["queuecache"]["list"])) {
			// Try to get the queue for the specified department
			foreach ($_SWIFT["queuecache"]["list"] as $key=>$val)
			{
				if ($val["departmentid"] == $this->ticket["departmentid"])
				{
					return iif(!empty($val["customfromname"]), $val["customfromname"], $_SWIFT["staff"]["fullname"]);
				}
			}
		}

		if (empty($_SWIFT["staff"]["fullname"]))
		{
			return $_SWIFT["departmentcache"][$this->ticket["departmentid"]]["title"];
		}

		return $_SWIFT["staff"]["fullname"];
	}

	/**
	* Add an audit log etry for a given ticket
	*/
	function addAuditLogEntry($logtype, $actiontype, $actionmsg)
	{
		global $dbCore, $_SWIFT, $template;

		if (!$this->ticket)
		{
			return false;
		}

		$template->loadLanguageSection("tickets_auditlogs", TEMPLATE_FILE);

		$this->auditsql[] = "('". intval($this->ticket["ticketid"]) ."', '". $dbCore->escape($_SWIFT["staff"]["staffid"]) ."', '". $dbCore->escape($this->ticket["departmentid"]) ."', '". $dbCore->escape($this->ticket["userid"]) ."', '". DATENOW ."', '". intval($logtype) ."', '". intval($actiontype) ."','". $dbCore->escape($actionmsg) ."')";

		return true;
	}

	/**
	* Gets the ticket for the current staff
	*/
	function loadTicketDisplay()
	{
		global $dbCore, $_SWIFT;

		if (!$this->ticket)
		{
			return false;
		}

		$_assigns = getAssignedDepartments(MODULE_TICKETS);

		$_ticket = &$this->ticket;
		if (empty($_ticket["ticketid"]) || !in_array($_ticket["departmentid"], $_assigns))
		{
			return false;
		}

		// Get the notes for this ticket
		$_ticket["notes"] = array();
		$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."ticketnotes` WHERE (`typeid` = '". intval($_ticket["ticketid"]) ."' AND `notetype` = '". NOTE_TICKET ."') OR (`typeid` = '". intval($_ticket["userid"]) ."' AND `notetype` = '". NOTE_USER ."') ORDER BY `dateline` ASC;");
		while ($dbCore->nextRecord())
		{
			$_ticket["notes"][] = $dbCore->Record;
		}

		$this->loadTicketBilling();
		$this->loadTicketCustomFields();

		// Load the User
		$_user = array();
		if (!empty($_ticket["userid"]))
		{
			$_user = $dbCore->queryFetch("SELECT u.*, ug.*, u.slaplanid AS userslaplanid, ug.slaplanid AS usergroupslaplanid FROM `". TABLE_PREFIX ."users` AS u LEFT JOIN `". TABLE_PREFIX ."usergroups` AS ug ON (u.usergroupid = ug.usergroupid) WHERE u.userid = '". intval($_ticket["userid"]) ."';");
		}
		$_ticket["user"] = $_user;
		unset($_user);

		// Has Draft?
		if ($_ticket["hasdraft"] == "1")
		{
			$_draft = $dbCore->queryFetch("SELECT `contents` FROM `". TABLE_PREFIX ."ticketdrafts` WHERE `ticketid` = '". intval($_ticket["ticketid"]) ."';");
			$_ticket["draft"] = $_draft["contents"];
		}

		// Has Escalation Paths?
		if ($_ticket["isescalated"] == "1")
		{
			$_escalationpaths = array();
			$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."escalationpaths` WHERE `ticketid` = '". intval($_ticket["ticketid"]) ."';", 2);
			while ($dbCore->nextRecord(2))
			{
				$_escalationpaths[$dbCore->Record2["escalationpathid"]] = $dbCore->Record2;
			}

			$_ticket["escalationpaths"] = $_escalationpaths;
		}

		return true;
	}

	/**
	* Loads the billing entries for this ticket
	*/
	function loadTicketBilling()
	{
		global $dbCore, $_SWIFT;

		$_ticket = &$this->ticket;

		// Do we need to load time tracking entries?
		$_ticket["billing"] = $timetrack = $timetrackidlist = $timetrackgroups = array();
		$_ticket["totalworked"] = $_ticket["totalbilled"] = 0;
		if ($_ticket["hasbilling"] == "1")
		{
			$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."tickettimetrack` WHERE `ticketid` = '". intval($this->ticket["ticketid"]) ."' ORDER BY `timetrackid` ASC;");
			while ($dbCore->nextRecord())
			{
				$_ticket["billing"][$dbCore->Record["timetrackid"]] = $dbCore->Record;
				$_ticket["billing"][$dbCore->Record["timetrackid"]]["fields"] = array();
				$_ticket["totalworked"] += intval($dbCore->Record["timespent"]);
				$_ticket["totalbilled"] += intval($dbCore->Record["timebillable"]);
				$_ticket["timetrackidlist"][] = $dbCore->Record["timetrackid"];
			}
		}

		return true;
	}

	/**
	* Loads the custom fields and its values
	*/
	function loadTicketCustomFields()
	{
		global $dbCore, $_SWIFT;

		$_ticket = &$this->ticket;

		// Get the Custom Fields
		$_ticket["fields"] = $_customfields = $customfieldidlist = $customfieldgroupidlist = $customfieldlinks = $cfvaluesql = $cfgrouptype = $cffieldref = $ttcfgroupidlist = $ttgrouppointer = array();
		//Mahesh Slaria: Staff & user ticket creation
		$dbCore->query("SELECT customfieldlinks.*, customfieldgroups.title AS grouptitle FROM `". TABLE_PREFIX ."customfieldlinks` AS customfieldlinks LEFT JOIN `". TABLE_PREFIX ."customfieldgroups` AS customfieldgroups ON (customfieldgroups.customfieldgroupid = customfieldlinks.customfieldgroupid) WHERE (customfieldlinks.linktype = '". CUSTOMFIELD_STAFFTICKET ."' AND customfieldlinks.typeid = '". intval($this->ticket["ticketid"]) ."') OR (customfieldlinks.linktype = '". CUSTOMFIELD_USERTICKET ."' AND customfieldlinks.typeid = '". intval($this->ticket["ticketid"]) ."') OR (customfieldlinks.linktype = '". CUSTOMFIELD_STAFFUSERTICKET ."' AND customfieldlinks.typeid = '". intval($this->ticket["ticketid"]) ."') OR (customfieldlinks.linktype = '". CUSTOMFIELD_TIMETRACK ."' AND customfieldlinks.typeid IN (". buildIN($this->ticket["timetrackidlist"]) .")) OR (customfieldlinks.linktype = '". CUSTOMFIELD_USER ."' AND customfieldlinks.typeid = '". intval($this->ticket["userid"]) ."') OR (customfieldlinks.linktype = '". CUSTOMFIELD_USERGROUP ."' AND customfieldlinks.typeid = '". intval($this->ticket["usergroupid"]) ."') ORDER BY customfieldgroups.displayorder ASC;");
		while ($dbCore->nextRecord())
		{
			$customfieldlinks[$dbCore->Record["customfieldgroupid"]] = $dbCore->Record;
			$customfieldlinks[$dbCore->Record["customfieldgroupid"]]["fields"] = array();
			$cfgrouptype[$dbCore->Record["customfieldgroupid"]] = $dbCore->Record["linktype"];
			$customfieldgroupidlist[] = $dbCore->Record["customfieldgroupid"];
			if ($dbCore->Record["linktype"] == CUSTOMFIELD_TIMETRACK)
			{
				$ttcfgroupidlist[] = $dbCore->Record["customfieldgroupid"];
			}
		}

		if (count($customfieldgroupidlist))
		{
			$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."customfields` WHERE `customfieldgroupid` IN (". buildIN($customfieldgroupidlist) .") ORDER BY `displayorder` ASC;");
			while ($dbCore->nextRecord())
			{
				$cfref = &$customfieldlinks[$dbCore->Record["customfieldgroupid"]]["fields"];
				$cffieldref[$dbCore->Record["customfieldid"]] = $dbCore->Record["customfieldgroupid"];
				$cfref[$dbCore->Record["customfieldid"]] = $dbCore->Record;
				$customfieldidlist[] = $dbCore->Record["customfieldid"];
//Mahesh Slaria: Staff & user ticket creation
				if ($cfgrouptype[$dbCore->Record["customfieldgroupid"]] == CUSTOMFIELD_USERTICKET || $cfgrouptype[$dbCore->Record["customfieldgroupid"]] == CUSTOMFIELD_STAFFTICKET || $cfgrouptype[$dbCore->Record["customfieldgroupid"]] == CUSTOMFIELD_STAFFUSERTICKET)
				{
					$cfvaluesql[] = "(`customfieldid` = '". intval($dbCore->Record["customfieldid"]) ."' AND `typeid` = '". intval($this->ticket["ticketid"]) ."')";
				} else if ($cfgrouptype[$dbCore->Record["customfieldgroupid"]] == CUSTOMFIELD_TIMETRACK) {
					$cfvaluesql[] = "(`customfieldid` = '". intval($dbCore->Record["customfieldid"]) ."' AND `typeid` IN (". buildIN($this->ticket["timetrackidlist"]) ."))";
				} else if ($cfgrouptype[$dbCore->Record["customfieldgroupid"]] == CUSTOMFIELD_USER) {
					$cfvaluesql[] = "(`customfieldid` = '". intval($dbCore->Record["customfieldid"]) ."' AND `typeid` = '". intval($this->ticket["userid"]) ."')";
				} else if ($cfgrouptype[$dbCore->Record["customfieldgroupid"]] == CUSTOMFIELD_USERGROUP) {
					$cfvaluesql[] = "(`customfieldid` = '". intval($dbCore->Record["customfieldid"]) ."' AND `typeid` = '". intval($this->ticket["usergroupid"]) ."')";
				}
			}

			if (count($cfvaluesql))
			{
				$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."customfieldvalues` WHERE ". implode(" OR ", $cfvaluesql) .";");
				while ($dbCore->nextRecord())
				{
					$cfgroupref = &$customfieldlinks[$cffieldref[$dbCore->Record["customfieldid"]]];
					if ($cfgroupref["linktype"] == CUSTOMFIELD_TIMETRACK)
					{
						$dcfref = &$_ticket["billing"][$dbCore->Record["typeid"]]["fields"][$dbCore->Record["customfieldid"]];
						$dcfref["title"] = $cfref[$dbCore->Record["customfieldid"]]["title"];
					} else {
						$dcfref = &$customfieldlinks[$cffieldref[$dbCore->Record["customfieldid"]]]["fields"][$dbCore->Record["customfieldid"]];
					}
					if ($dbCore->Record["isserialized"] == 1)
					{
						$dcfref["fieldvalue"][] = $dbCore->Record["fieldvalue"];
						$dcfref["valuearray"] = true;
					} else {
						$dcfref["fieldvalue"] = $dbCore->Record["fieldvalue"];
						$dcfref["valuearray"] = false;
					}
				}
				$_ticket["fields"] = $customfieldlinks;
				$_ticket["cfref"] = $cfref;
				unset($_customfields);
			}
		}

		return true;
	}

	/**
	* Get the Audit Logs for the ticket
	*/
	function getAuditLogs()
	{
		global $dbCore, $_SWIFT;

		if (!$this->ticket)
		{
			return false;
		}

		// Now get the audit log for this ticket.
		$_auditlogs = array();
		$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."auditlogs` WHERE `ticketid` = '". intval($this->ticket["ticketid"]) ."' ORDER BY `auditlogid` ASC;");
		while ($dbCore->nextRecord())
		{
			$_auditlogs[$dbCore->Record["auditlogid"]] = $dbCore->Record;
		}

		return $_auditlogs;
	}

	/**
	* Get all the ticket posts
	*/
	function getTicketPosts($limit = false, $offset = false, $order = "asc", $isclientcp = false, $nobr = false)
	{
		global $dbCore, $_SWIFT, $mimelist;

		$_ticket = &$this->ticket;

		// Get all the posts for this ticket
		$_posts = $ticketpostidlist = array();
		$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."ticketposts` WHERE `ticketid` = '". intval($_ticket["ticketid"]) ."' ORDER BY `ticketpostid` ".iif($order=="asc", "ASC", "DESC"). iif($limit&&$limit!=-1, " LIMIT ". intval($offset) .",". intval($limit)) .";");
		while ($dbCore->nextRecord())
		{
			if ($isclientcp && $_SWIFT["settings"]["t_cthirdparty"] != "1" && ($dbCore->Record["creator"] == POST_THIRDPARTY || !empty($dbCore->Record["emailto"]))) // We are not supposed to display the third party replies to client
			{
				continue;
			}

			$ticketpostidlist[] = $dbCore->Record["ticketpostid"];
			$_posts[$dbCore->Record["ticketpostid"]] = $dbCore->Record;
			$_posts[$dbCore->Record["ticketpostid"]]["attachments"] = $_posts[$dbCore->Record["ticketpostid"]]["notes"] = array();
			if ($isclientcp)
			{
				if ($dbCore->Record["creator"] == POST_STAFF)
				{
					$_posts[$dbCore->Record["ticketpostid"]]["creator"] = "staff";
				} else if ($dbCore->Record["creator"] == POST_THIRDPARTY) {
					$_posts[$dbCore->Record["ticketpostid"]]["creator"] = "thirdparty";
				} else if ($dbCore->Record["creator"] == POST_RECIPIENT) {
					$_posts[$dbCore->Record["ticketpostid"]]["creator"] = "recipient";
				} else {
					$_posts[$dbCore->Record["ticketpostid"]]["creator"] = "user";
				}
			}

			if ($nobr == true)
			{
				$_posts[$dbCore->Record["ticketpostid"]]["contents"] = $dbCore->Record["contents"];
			} else {
				$_posts[$dbCore->Record["ticketpostid"]]["contents"] = $this->returnProcessedContent($dbCore->Record["contents"]);
			}
			$_posts[$dbCore->Record["ticketpostid"]]["contentstext"] = strip_tags($dbCore->Record["contents"]);

			$_posts[$dbCore->Record["ticketpostid"]]["date"] = edate($_SWIFT["settings"]["dt_datetimeformat"], $dbCore->Record["dateline"]);
			$_posts[$dbCore->Record["ticketpostid"]]["attachmentcount"] = 0;
		}

		// If this ticket has attachments then get them for this ticket
		if ($_ticket["hasattachments"] == 1)
		{
			$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."attachments` WHERE `ticketpostid` IN (". buildIN($ticketpostidlist) .");");
			while ($dbCore->nextRecord())
			{
				$_posts[$dbCore->Record["ticketpostid"]]["attachments"][$dbCore->Record["attachmentid"]] = $dbCore->Record;
				$_attachment = &$_posts[$dbCore->Record["ticketpostid"]]["attachments"][$dbCore->Record["attachmentid"]];
				if ($isclientcp)
				{
					$extension = getFileExtension($dbCore->Record["filename"]);
					$mimedata = $mimelist[$extension];
					if (!empty($mimedata[1]))
					{
						$icon = $mimedata[1];
					} else {
						$icon = "mimeico_blank.gif";
					}

					$_attachment["icon"] = $icon;
					$_attachment["attachmentsize"] = formattedSize($dbCore->Record["filesize"]);
					$_posts[$dbCore->Record["ticketpostid"]]["attachmentcount"]++;
				}
			}
		}

		return $_posts;
	}

	function setSLAPlan($slaplanid)
	{
		$this->updatesql[] = "`ticketslaplanid` = '". intval($slaplanid) ."'";
		$this->updatesql[] = "`slaplanid` = '". intval($slaplanid) ."'";
		$this->ticket["ticketslaplanid"] = $slaplanid;
		$this->ticket["slaplanid"] = $slaplanid;

		if (defined("SLADEBUG"))
		{
			$this->addTicketNote(NOTE_TICKET, 0, "Setting SLA Plan: ".$slaplanid);
		}

		return true;
	}

	/**
	* Resets the SLA Timeline for a ticket
	*/
	function resetSLATimeline($slaplanid = false, $_escalated = false)
	{
		global $dbCore, $_SWIFT;

		if (!$this->ticket)
		{
			return false;
		}

		require_once ("./modules/tickets/functions_sla.php");

		if ($slaplanid)
		{
			if (defined("SLADEBUG"))
			{
				$this->addTicketNote(NOTE_TICKET, 0, "Reset Timeline, Setting SLA Plan: ".$slaplanid);
			}
			$this->setSLAPlan($slaplanid);
		}

		// First try to see if this ticket has a custom sla plan set for it.
		$_slaplanid = false;
		if (!empty($slaplanid))
		{
			$_slaplanid = $slaplanid;
		} else if (!empty($this->ticket["ticketslaplanid"])) {
			$_slaplanid = $this->ticket["ticketslaplanid"];
		} else if (!empty($this->ticket["slaplanid"])) {
			$_slaplanid = $this->ticket["slaplanid"];
		} else if (!empty($this->ticket["userid"])) {
			if (defined("SLADEBUG"))
			{
				$this->addTicketNote(NOTE_TICKET, 0, "Setting SLA Plan from User/Group");
			}
			// Now we need to get both user sla plan and user group sla plan
			$_sladetails = $dbCore->queryFetch("SELECT users.slaplanid AS userslaplanid, usergroups.slaplanid AS groupslaplanid FROM `". TABLE_PREFIX ."users` AS users LEFT JOIN `". TABLE_PREFIX ."usergroups` AS usergroups ON (users.usergroupid = usergroups.usergroupid) WHERE users.userid = '". intval($this->ticket["userid"]) ."';");
			if (!empty($_sladetails["userslaplanid"]))
			{
				$_slaplanid = $_sladetails["userslaplanid"];
			} else if (!empty($_sladetails["groupslaplanid"])) {
				$_slaplanid = $_sladetails["groupslaplanid"];
			}
		}

		if ($_escalated == true)
		{
//			echo "Fetching SLA Plan from Scratch<BR />";
			if (defined("SLADEBUG"))
			{
				$this->addTicketNote(NOTE_TICKET, 0, "Ticket has been escalated, Ignoring: ".$this->ticket["ticketslaplanid"]);
			}
			$_ignoreslaplanid = $this->ticket["ticketslaplanid"];
			unset($_slaplanid);
		} else {
			$_ignoreslaplanid = false;
		}

		$_duedebug = '';
		$_sla = getDueTimeline($this->ticket["departmentid"], $this->ticket["ticketstatusid"], $this->ticket["priorityid"], $_slaplanid, false, $_ignoreslaplanid, $_duedebug);
		if (defined("SLADEBUG"))
		{
			$this->addTicketNote(NOTE_TICKET, 0, "Due Debug\n".$_duedebug);
		}

		
		if (!$_sla)
		{
//			echo "Failed to get SLA Plan<BR />";
			$_duetimeline = "0";
			$_slaplanid = "0";
		} else {
//			echo "Got the SLA Plan: ".$_sla["slaplanid"]."<BR />";
			$_duetimeline = $_sla["duetimeline"];
			$_slaplanid = $_sla["slaplanid"];
		}

//		$this->updateField("`isescalated` = '0'");
		$this->updateField("`duetime` = '". intval($_duetimeline) ."'");
		$this->updateField("`slaplanid` = '". intval($_slaplanid) ."'");

		if ($_slaplanid)
		{
			$this->addAuditLogEntry(LOG_SYSTEM, ACTION_SLA, sprintf($_SWIFT["language"]["al_sla"], htmlspecialchars($_SWIFT["slaplancache"][$_slaplanid]["title"])));
		}
		if ($_duetimeline)
		{
			$this->addAuditLogEntry(LOG_SYSTEM, ACTION_DUE, sprintf($_SWIFT["language"]["al_due"], edate($_SWIFT["settings"]["dt_datetimeformat"], $_duetimeline)));
		}

		return true;
	}

	/**
	* Flag a given ticket
	*/
	function flagTicket($flagtype)
	{
		global $dbCore, $_SWIFT;

		if (!$this->ticket)
		{
			return false;
		}

		if ($this->ticket["flagtype"] == $flagtype)
		{
			return true;
		}

		$flagtext = array(FLAG_PURPLE => $_SWIFT["language"]["purpleflag"], FLAG_ORANGE => $_SWIFT["language"]["orangeflag"], FLAG_GREEN => $_SWIFT["language"]["greenflag"], FLAG_YELLOW => $_SWIFT["language"]["yellowflag"], FLAG_RED => $_SWIFT["language"]["redflag"], FLAG_BLUE => $_SWIFT["language"]["blueflag"]);

		$this->updateField("`flagtype` = '". intval($flagtype) ."'");
		$this->alerts->raiseAlert(ALERT_FLAG, array("flag" => $flagtext[$flagtype], "flagby" => $_SWIFT["staff"]["fullname"]));


		if (empty($_SWIFT["staff"]["fullname"]))
		{
			$userfullname = $_SWIFT["language"]["alsystem"];
		} else {
			$userfullname = $_SWIFT["staff"]["fullname"];
		}

		$this->addAuditLogEntry($this->logtype, ACTION_FLAG, sprintf($_SWIFT["language"]["al_flag"], htmlspecialchars($flagtext[$flagtype]), htmlspecialchars($userfullname)));

		return true;
	}

	/**
	* Clear Flag on this Ticket
	*/
	function clearFlag()
	{
		global $dbCore, $_SWIFT;

		if (!$this->ticket)
		{
			return false;
		}

		$this->updateField("`flagtype` = '0'");
		$this->addAuditLogEntry($this->logtype, ACTION_FLAG, sprintf($_SWIFT["language"]["al_flagclear"], htmlspecialchars($_SWIFT["staff"]["fullname"])));

		return true;
	}

	/**
	* Export the Ticket as XML
	*/
	function exportXML()
	{
		global $dbCore, $_SWIFT;

		if (!$this->ticket)
		{
			return false;
		}

		$this->loadTicketDisplay();

		require_once ("./includes/functions_xml.php");
		$xml = new XML();
		$xml->addComment(sprintf($_SWIFT["language"]["generationdate"], edate($_SWIFT["settings"]["dt_datetimeformat"], DATENOW)));
		$xml->addParentTag("ticket");
			$xml->addTag("ticketid", $this->ticket["ticketid"]);
			$xml->addTag("ticketmaskid", $this->ticket["ticketmaskid"]);
			$xml->addTag("departmentid", $this->ticket["departmentid"]);
			$xml->addTag("department", $_SWIFT["departmentcache"][$this->ticket["departmentid"]]["title"]);
			$xml->addTag("ticketstatusid", $this->ticket["ticketstatusid"]);
			$xml->addTag("ticketstatus", $_SWIFT["statuscache"][$this->ticket["ticketstatusid"]]["title"]);
			$xml->addTag("priorityid", $this->ticket["priorityid"]);
			$xml->addTag("priority", $_SWIFT["prioritycache"][$this->ticket["priorityid"]]["title"]);
			$xml->addTag("emailqueueid", $this->ticket["emailqueueid"]);
			$xml->addTag("emailqueue", $_SWIFT["queuecache"][$this->ticket["emailqueueid"]]["email"]);
			$xml->addTag("userid", $this->ticket["userid"]);
			$xml->addTag("ownerstaffid", $this->ticket["ownerstaffid"]);
			$xml->addTag("fullname", $this->ticket["fullname"]);
			$xml->addTag("email", $this->ticket["email"]);
			$xml->addTag("lastreplier", $this->ticket["lastreplier"]);
			$xml->addTag("subject", $this->ticket["subject"]);
			$xml->addTag("dateline", $this->ticket["dateline"]);
			$xml->addTag("lastactivity", $this->ticket["lastactivity"]);
			$xml->addTag("laststaffreplytime", $this->ticket["laststaffreplytime"]);
			$xml->addTag("slaplanid", $this->ticket["slaplanid"]);
			$xml->addTag("duetime", $this->ticket["duetime"]);
			$xml->addTag("totalreplies", $this->ticket["totalreplies"]);
			$xml->addTag("ipaddress", $this->ticket["ipaddress"]);
			$xml->addTag("flagtype", $this->ticket["flagtype"]);
			$xml->addTag("timeworked", $this->ticket["timeworked"]);
			$xml->addTag("edited", $this->ticket["edited"]);
			$xml->addTag("editedbystaffid", $this->ticket["editedbystaffid"]);
			$xml->addTag("editeddateline", $this->ticket["editeddateline"]);

			$_posts = $this->getTicketPosts();
			foreach ($_posts as $key=>$val)
			{
				$xml->addParentTag("post");
					$xml->addTag("ticketpostid", $val["ticketpostid"]);
					$xml->addTag("userid", $val["userid"]);
					$xml->addTag("dateline", $val["dateline"]);
					$xml->addTag("fullname", $val["fullname"]);
					$xml->addTag("email", $val["email"]);
					$xml->addTag("subject", $val["subject"]);
					$xml->addTag("ipaddress", $val["ipaddress"]);
					$xml->addTag("edited", $val["edited"]);
					$xml->addTag("editedbystaffid", $val["editedbystaffid"]);
					$xml->addTag("editeddateline", $val["editeddateline"]);
					$xml->addTag("creator", $val["creator"]);
					$xml->addTag("ishtml", $val["ishtml"]);
					$xml->addTag("contenthash", $val["contenthash"]);
					$xml->addTag("contents", $val["contents"]);
				$xml->endParentTag("post");
			}
		$xml->endParentTag("ticket");

		$xmldata = $xml->returnXML();

		$this->addAuditLogEntry($this->logtype, ACTION_XMLEXPORT, sprintf($_SWIFT["language"]["al_xmlexport"], htmlspecialchars($_SWIFT["staff"]["fullname"])));

		$filename = "ticket_".str_replace("-","_",$this->ticket["ticketmaskid"]).".xml";

		if(isset($_SERVER['HTTP_USER_AGENT']) && preg_match("/MSIE/", $_SERVER['HTTP_USER_AGENT'])) {
			// IE Bug in download name workaround
			ini_set( 'zlib.output_compression','Off' );
		}

		header("Content-Type: application/force-download");

		if (strpos($_SERVER['HTTP_USER_AGENT'], "MSIE")){
			header("Content-Disposition: attachment; filename=\"". $filename ."\"");
		} else{
			header("Content-Disposition: attachment; filename=\"". $filename ."\"");
		}

		header("Content-Transfer-Encoding: binary");
		header("Content-Length: ". strlen($xmldata));

		echo $xmldata;
	}

	/**
	* Export the ticket as PDF
	*/
	function exportPDF()
	{
		global $_SWIFT, $dbCore;

		if (!$this->ticket)
		{
			return false;
		}

		require_once ("./includes/functions_pdf.php");
		$_ticket = &$this->ticket;
		$_ticket["date"] = edate($_SWIFT["settings"]["dt_datetimeformat"], $_ticket["dateline"]);

		$htmloutput = "";
		$_posts = $this->getTicketPosts();
		foreach ($_posts as $key=>$val)
		{
			if ($val["creator"] == POST_STAFF)
			{
				$tag = "staff";
			} else {
				$tag = "user";
			}
			$htmloutput .= '<'. $tag .'>'. sprintf($_SWIFT["language"]["pdfrow"], $val["fullname"], edate($_SWIFT["settings"]["dt_datetimeformat"], $val["dateline"])).'</'. $tag .'><br><pre>'. getProcessedHTML(trim($val["contents"])) .'</pre><br><br>
			<HR>';
		}

		$str=array(
			'<br />' => '<br>',
			'<hr />' => '<hr>',
			'[r]' => '<red>',
			'[/r]' => '</red>',
			'[l]' => '<blue>',
			'[/l]' => '</blue>',
			'&#8220;' => '"',
			'&#8221;' => '"',
			'&#8222;' => '"',
			'&#8230;' => '...',
			'&#8217;' => '\''
		);
		foreach ($str as $_from => $_to) $htmloutput = str_replace($_from,$_to,$htmloutput);

		$pdf = new PDF('P','mm','A4',$_ticket["ticketmaskid"],"",false);
		$pdf->Open();
		$pdf->SetCompression(true);
		$pdf->SetCreator(_iso2ascii($_SWIFT["settings"]["general_companyname"]));
		$pdf->SetDisplayMode('real');
		$pdf->SetTitle(_iso2ascii($_ticket["subject"]));
		$pdf->SetAuthor(_iso2ascii($_SWIFT["settings"]["general_companyname"]));
		$pdf->AddPage();

		$pdf->PutMainTitle(_iso2ascii($_ticket["subject"]));
		$pdf->PutMinorTitle(_iso2ascii($_ticket["fullname"]));
		$pdf->PutMinorHeading(_iso2ascii($_SWIFT["language"]["createdon"]).edate($_SWIFT["settings"]["dt_datetimeformat"], $_ticket["dateline"]));
		$pdf->PutLine();


		$pdf->WriteHTML($htmloutput, $htmloutput);

		$filename = "ticket_".str_replace("-","_",$_ticket["ticketmaskid"]).'.pdf';
		$pdf->Output($filename, "D");

		$this->addAuditLogEntry($this->logtype, ACTION_PDFEXPORT, sprintf($_SWIFT["language"]["al_pdfexport"], htmlspecialchars($_SWIFT["staff"]["fullname"])));
	}

	/**
	* Marks the ticket as due
	*/
	function markAsDue($customtimeline = false)
	{
		global $_SWIFT;

		if (!$this->ticket)
		{
			return false;
		}

		if (!$customtimeline)
		{
			$customtimeline = DATENOW-1;
			$this->addAuditLogEntry($this->logtype, ACTION_DUE, sprintf($_SWIFT["language"]["al_duestaffoverdue"], htmlspecialchars($_SWIFT["staff"]["fullname"])));
		} else {
			$this->addAuditLogEntry($this->logtype, ACTION_DUE, sprintf($_SWIFT["language"]["al_duestaff"], edate($_SWIFT["settings"]["dt_datetimeformat"], $customtimeline), htmlspecialchars($_SWIFT["staff"]["fullname"])));
		}

		$this->updatesql[] = "`duetime` = '". intval($customtimeline) ."'";

		return true;
	}

	/**
	* Clears the Due Timeline
	*/
	function clearDue()
	{
		global $_SWIFT;

		if (!$this->ticket)
		{
			return false;
		}

		$this->updatesql[] = "`duetime` = '0'";
		$this->addAuditLogEntry($this->logtype, ACTION_DUE, sprintf($_SWIFT["language"]["al_duestaffclear"], htmlspecialchars($_SWIFT["staff"]["fullname"])));
		
		$this->duetimecleared = true;

		return true;
	}

	/**
	* Add Recipients to ticket
	*/
	function addRecipients($emaillist, $recipienttype)
	{
		global $dbCore, $_SWIFT;

		if (!_is_array($emaillist) || !$this->ticket)
		{
			return false;
		}

		// See if we already have the emails added to database..
		$_ticketemails = array();
		$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."ticketemails` WHERE `email` IN (". buildIN($emaillist) .");");
		while ($dbCore->nextRecord())
		{
			$dbCore->Record["email"] = strtolower($dbCore->Record["email"]);
			$_ticketemails[$dbCore->Record["email"]] = $dbCore->Record["ticketemailid"];
		}

		$_emailaddlist = $_emailaddsql = array();
		foreach ($emaillist as $key=>$val)
		{
			$val = strtolower($val);
			if (empty($_ticketemails[$val]) && isValidEmail($val))
			{
				$_emailaddlist[] = strtolower($val);
				$_emailaddsql[] = "('". $dbCore->escape(strtolower($val)) ."')";
			}
		}

		if (count($_emailaddsql))
		{
			$dbCore->query("INSERT INTO `". TABLE_PREFIX ."ticketemails` (`email`) VALUES ". implode(",",$_emailaddsql).";");
			$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."ticketemails` WHERE `email` IN (". buildIN($_emailaddlist) .");");
			while ($dbCore->nextRecord())
			{
				$_ticketemails[$dbCore->Record["email"]] = $dbCore->Record["ticketemailid"];
			}
		}

		// Ok, By now we should have a valid list of emails.. assign the recipient to this ticket now
		$_recipientsql = array();
		foreach ($_ticketemails as $key=>$val)
		{
			$_recipientsql[] = "('". intval($this->ticket["ticketid"]) ."', '". intval($val) ."', '". intval($recipienttype) ."')";
		}
		if (count($_recipientsql))
		{
			$dbCore->query("REPLACE INTO `". TABLE_PREFIX ."ticketrecipients` (`ticketid`, `ticketemailid`, `recipienttype`) VALUES ". implode(",", $_recipientsql) .";");
		}

		return true;
	}

	/**
	* Gets the recipients for the current ticket
	*/
	function getRecipients()
	{
		global $dbCore;

		$_recipients = array();
		$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."ticketrecipients` AS ticketrecipients LEFT JOIN `". TABLE_PREFIX ."ticketemails` AS ticketemails ON (ticketrecipients.ticketemailid = ticketemails.ticketemailid) WHERE ticketrecipients.ticketid = '". intval($this->ticket["ticketid"]) ."';");
		while ($dbCore->nextRecord())
		{
			$_recipients[] = $dbCore->Record;
		}

		return $_recipients;
	}

	/**
	* Update Fullname, Email, Subject
	*/
	function updateProperties($subject, $email, $fullname)
	{
		global $dbCore, $_SWIFT;

		if (!$this->ticket)
		{
			return false;
		}

		$this->updatesql[] = "`subject` = '". $dbCore->escape($subject) ."'";
		$this->updatesql[] = "`email` = '". $dbCore->escape($email) ."'";
		$this->updatesql[] = "`fullname` = '". $dbCore->escape($fullname) ."'";
		
		if ($subject != $this->ticket["subject"])
		{
			require_once ("./modules/tickets/functions_search.php");
			buildTicketPostIndex($this->ticket["firstpostid"], $subject, $subject);
		}

		return true;
	}

	/**
	* Filters Junk Chars for XML Validation
	*/
	function filterJunkCharacters($_data)
	{
		$_eregreplacedata = "AXwCfAN8BHwFfAZ8B3wIfAt8DHwOfA98EHwRfBJ8E3wUfBV8FnwXfBh8GXwafBt8HHwdfB58H3ztIIB87SCBfO0ggnztIIN87SCEfO0ghXztIIZ87SCHfO0giHztIIl87SCKfO0gi3ztIIx87SCNfO0gjnztII987SCQfO0gkXztIJJ87SCTfO0glHztIJV87SCWfO0gl3ztIJh87SCZfO0gmnztIJt87SCcfO0gnXztIJ587SCffO0gIHztIKF87SCifO0go3ztIKR87SClfO0gpnztIKd87SCofO0gqXztIKp87SCrfO0grHztIK187SCufO0gr3ztILB87SCxfO0gsnztILN87SC0fO0gtXztILZ87SC3fO0guHztILl87SC6fO0gu3ztILx87SC9fO0gvnztIL987aGAfO2hgXztoYJ87aGDfO2hhHztoYV87aGGfO2hh3ztoYh87aGJfO2hinztoYt87aGMfO2hjXztoY587aGPfO2hkHztoZF87aGSfO2hk3ztoZR87aGVfO2hlnztoZd87aGYfO2hmXztoZp87aGbfO2hnHztoZ187aGefO2hn3ztoSB87aGhfO2honztoaN87aGkfO2hpXztoaZ87aGnfO2hqHztoal87aGqfO2hq3ztoax87aGtfO2hrnztoa987aGwfO2hsXztobJ87aGzfO2htHztobV87aG2fO2ht3ztobh87aG5fO2hunztobt87aG8fO2hvXztob587aG/fO2igHztooF87aKCfO2ig3ztooR87aKFfO2ihnztood87aKIfO2iiXztoop87aKLfO2ijHztoo187aKOfO2ij3ztopB87aKRfO2iknztopN87aKUfO2ilXztopZ87aKXfO2imHztopl87aKafO2im3ztopx87aKdfO2innztop987aIgfO2ioXztoqJ87aKjfO2ipHztoqV87aKmfO2ip3ztoqh87aKpfO2iqnztoqt87aKsfO2irXztoq587aKvfO2isHztorF87aKyfO2is3ztorR87aK1fO2itnztord87aK4fO2iuXztorp87aK7fO2ivHztor187aK+fO2iv3zto4B87aOBfO2jgnzto4N87aOEfO2jhXzto4Z87aOHfO2jiHzto4l87aOKfO2ji3zto4x87aONfO2jjnzto4987aOQfO2jkXzto5J87aOTfO2jlHzto5V87aOWfO2jl3zto5h87aOZfO2jmnzto5t87aOcfO2jnXzto5587aOffO2jIHzto6F87aOifO2jo3zto6R87aOlfO2jpnzto6d87aOofO2jqXzto6p87aOrfO2jrHzto6187aOufO2jr3zto7B87aOxfO2jsnzto7N87aO0fO2jtXzto7Z87aO3fO2juHzto7l87aO6fO2ju3zto7x87aO9fO2jvnzto7987aSAfO2kgXztpIJ87aSDfO2khHztpIV87aSGfO2kh3ztpIh87aSJfO2kinztpIt87aSMfO2kjXztpI587aSPfO2kkHztpJF87aSSfO2kk3ztpJR87aSVfO2klnztpJd87aSYfO2kmXztpJp87aSbfO2knHztpJ187aSefO2kn3ztpCB87aShfO2konztpKN87aSkfO2kpXztpKZ87aSnfO2kqHztpKl87aSqfO2kq3ztpKx87aStfO2krnztpK987aSwfO2ksXztpLJ87aSzfO2ktHztpLV87aS2fO2kt3ztpLh87aS5fO2kunztpLt87aS8fO2kvXztpL587aS/fO2lgHztpYF87aWCfO2lg3ztpYR87aWFfO2lhnztpYd87aWIfO2liXztpYp87aWLfO2ljHztpY187aWOfO2lj3ztpZB87aWRfO2lknztpZN87aWUfO2llXztpZZ87aWXfO2lmHztpZl87aWafO2lm3ztpZx87aWdfO2lnnztpZ987aUgfO2loXztpaJ87aWjfO2lpHztpaV87aWmfO2lp3ztpah87aWpfO2lqnztpat87aWsfO2lrXztpa587aWvfO2lsHztpbF87aWyfO2ls3ztpbR87aW1fO2ltnztpbd87aW4fO2luXztpbp87aW7fO2lvHztpb187aW+fO2lv3ztpoB87aaBfO2mgnztpoN87aaEfO2mhXztpoZ87aaHfO2miHztpol87aaKfO2mi3ztpox87aaNfO2mjnztpo987aaQfO2mkXztppJ87aaTfO2mlHztppV87aaWfO2ml3ztpph87aaZfO2mmnztppt87aacfO2mnXztpp587aaffO2mIHztpqF87aaifO2mo3ztpqR87aalfO2mpnztpqd87aaofO2mqXztpqp87aarfO2mrHztpq187aaufO2mr3ztprB87aaxfO2msnztprN87aa0fO2mtXztprZ87aa3fO2muHztprl87aa6fO2mu3ztprx87aa9fO2mvnztpr987aeAfO2ngXztp4J87aeDfO2nhHztp4V87aeGfO2nh3ztp4h87aeJfO2ninztp4t87aeMfO2njXztp4587aePfO2nkHztp5F87aeSfO2nk3ztp5R87aeVfO2nlnztp5d87aeYfO2nmXztp5p87aebfO2nnHztp5187aeefO2nn3ztpyB87aehfO2nonztp6N87aekfO2npXztp6Z87aenfO2nqHztp6l87aeqfO2nq3ztp6x87aetfO2nrnztp6987aewfO2nsXztp7J87aezfO2ntHztp7V87ae2fO2nt3ztp7h87ae5fO2nunztp7t87ae8fO2nvXztp7587ae/fO2ogHztqIF87aiCfO2og3ztqIR87aiFfO2ohnztqId87aiIfO2oiXztqIp87aiLfO2ojHztqI187aiOfO2oj3ztqJB87aiRfO2oknztqJN87aiUfO2olXztqJZ87aiXfO2omHztqJl87aiafO2om3ztqJx87aidfO2onnztqJ987aggfO2ooXztqKJ87aijfO2opHztqKV87aimfO2op3ztqKh87aipfO2oqnztqKt87aisfO2orXztqK587aivfO2osHztqLF87aiyfO2os3ztqLR87ai1fO2otnztqLd87ai4fO2ouXztqLp87ai7fO2ovHztqL187ai+fO2ov3ztqYB87amBfO2pgnztqYN87amEfO2phXztqYZ87amHfO2piHztqYl87amKfO2pi3ztqYx87amNfO2pjnztqY987amQfO2pkXztqZJ87amTfO2plHztqZV87amWfO2pl3ztqZh87amZfO2pmnztqZt87amcfO2pnXztqZ587amffO2pIHztqaF87amifO2po3ztqaR87amlfO2ppnztqad87amofO2pqXztqap87amrfO2prHztqa187amufO2pr3ztqbB87amxfO2psnztqbN87am0fO2ptXztqbZ87am3fO2puHztqbl87am6fO2pu3ztqbx87am9fO2pvnztqb987aqAfO2qgXztqoJ87aqDfO2qhHztqoV87aqGfO2qh3ztqoh87aqJfO2qinztqot87aqMfO2qjXztqo587aqPfO2qkHztqpF87aqSfO2qk3ztqpR87aqVfO2qlnztqpd87aqYfO2qmXztqpp87aqbfO2qnHztqp187aqefO2qn3ztqiB87aqhfO2qonztqqN87aqkfO2qpXztqqZ87aqnfO2qqHztqql87aqqfO2qq3ztqqx87aqtfO2qrnztqq987aqwfO2qsXztqrJ87aqzfO2qtHztqrV87aq2fO2qt3ztqrh87aq5fO2qunztqrt87aq8fO2qvXztqr587aq/fO2rgHztq4F87auCfO2rg3ztq4R87auFfO2rhnztq4d87auIfO2riXztq4p87auLfO2rjHztq4187auOfO2rj3ztq5B87auRfO2rknztq5N87auUfO2rlXztq5Z87auXfO2rmHztq5l87auafO2rm3ztq5x87audfO2rnnztq5987asgfO2roXztq6J87aujfO2rpHztq6V87aumfO2rp3ztq6h87aupfO2rqnztq6t87ausfO2rrXztq6587auvfO2rsHztq7F87auyfO2rs3ztq7R87au1fO2rtnztq7d87au4fO2ruXztq7p87au7fO2rvHztq7187au+fO2rv3ztrIB87ayBfO2sgnztrIN87ayEfO2shXztrIZ87ayHfO2siHztrIl87ayKfO2si3ztrIx87ayNfO2sjnztrI987ayQfO2skXztrJJ87ayTfO2slHztrJV87ayWfO2sl3ztrJh87ayZfO2smnztrJt87aycfO2snXztrJ587ayffO2sIHztrKF87ayifO2so3ztrKR87aylfO2spnztrKd87ayofO2sqXztrKp87ayrfO2srHztrK187ayufO2sr3ztrLB87ayxfO2ssnztrLN87ay0fO2stXztrLZ87ay3fO2suHztrLl87ay6fO2su3ztrLx87ay9fO2svnztrL987a2AfO2tgXztrYJ87a2DfO2thHztrYV87a2GfO2th3ztrYh87a2JfO2tinztrYt87a2MfO2tjXztrY587a2PfO2tkHztrZF87a2SfO2tk3ztrZR87a2VfO2tlnztrZd87a2YfO2tmXztrZp87a2bfO2tnHztrZ187a2efO2tn3ztrSB87a2hfO2tonztraN87a2kfO2tpXztraZ87a2nfO2tqHztral87a2qfO2tq3ztrax87a2tfO2trnztra987a2wfO2tsXztrbJ87a2zfO2ttHztrbV87a22fO2tt3ztrbh87a25fO2tunztrbt87a28fO2tvXztrb587a2/fO2ugHztroF87a6CfO2ug3ztroR87a6FfO2uhnztrod87a6IfO2uiXztrop87a6LfO2ujHztro187a6OfO2uj3ztrpB87a6RfO2uknztrpN87a6UfO2ulXztrpZ87a6XfO2umHztrpl87a6afO2um3ztrpx87a6dfO2unnztrp987a4gfO2uoXztrqJ87a6jfO2upHztrqV87a6mfO2up3ztrqh87a6pfO2uqnztrqt87a6sfO2urXztrq587a6vfO2usHztrrF87a6yfO2us3ztrrR87a61fO2utnztrrd87a64fO2uuXztrrp87a67fO2uvHztrr187a6+fO2uv3ztr4B87a+BfO2vgnztr4N87a+EfO2vhXztr4Z87a+HfO2viHztr4l87a+KfO2vi3ztr4x87a+NfO2vjnztr4987a+QfO2vkXztr5J87a+TfO2vlHztr5V87a+WfO2vl3ztr5h87a+ZfO2vmnztr5t87a+cfO2vnXztr5587a+ffO2vIHztr6F87a+ifO2vo3ztr6R87a+lfO2vpnztr6d87a+ofO2vqXztr6p87a+rfO2vrHztr6187a+ufO2vr3ztr7B87a+xfO2vsnztr7N87a+0fO2vtXztr7Z87a+3fO2vuHztr7l87a+6fO2vu3ztr7x87a+9fO2vvnztr7987bCAfO2wgXztsIJ87bCDfO2whHztsIV87bCGfO2wh3ztsIh87bCJfO2winztsIt87bCMfO2wjXztsI587bCPfO2wkHztsJF87bCSfO2wk3ztsJR87bCVfO2wlnztsJd87bCYfO2wmXztsJp87bCbfO2wnHztsJ187bCefO2wn3ztsCB87bChfO2wonztsKN87bCkfO2wpXztsKZ87bCnfO2wqHztsKl87bCqfO2wq3ztsKx87bCtfO2wrnztsK987bCwfO2wsXztsLJ87bCzfO2wtHztsLV87bC2fO2wt3ztsLh87bC5fO2wunztsLt87bC8fO2wvXztsL587bC/fO2xgHztsYF87bGCfO2xg3ztsYR87bGFfO2xhnztsYd87bGIfO2xiXztsYp87bGLfO2xjHztsY187bGOfO2xj3ztsZB87bGRfO2xknztsZN87bGUfO2xlXztsZZ87bGXfO2xmHztsZl87bGafO2xm3ztsZx87bGdfO2xnnztsZ987bEgfO2xoXztsaJ87bGjfO2xpHztsaV87bGmfO2xp3ztsah87bGpfO2xqnztsat87bGsfO2xrXztsa587bGvfO2xsHztsbF87bGyfO2xs3ztsbR87bG1fO2xtnztsbd87bG4fO2xuXztsbp87bG7fO2xvHztsb187bG+fO2xv3ztsoB87bKBfO2ygnztsoN87bKEfO2yhXztsoZ87bKHfO2yiHztsol87bKKfO2yi3ztsox87bKNfO2yjnztso987bKQfO2ykXztspJ87bKTfO2ylHztspV87bKWfO2yl3ztsph87bKZfO2ymnztspt87bKcfO2ynXztsp587bKffO2yIHztsqF87bKifO2yo3ztsqR87bKlfO2ypnztsqd87bKofO2yqXztsqp87bKrfO2yrHztsq187bKufO2yr3ztsrB87bKxfO2ysnztsrN87bK0fO2ytXztsrZ87bK3fO2yuHztsrl87bK6fO2yu3ztsrx87bK9fO2yvnztsr987bOAfO2zgXzts4J87bODfO2zhHzts4V87bOGfO2zh3zts4h87bOJfO2zinzts4t87bOMfO2zjXzts4587bOPfO2zkHzts5F87bOSfO2zk3zts5R87bOVfO2zlnzts5d87bOYfO2zmXzts5p87bObfO2znHzts5187bOefO2zn3ztsyB87bOhfO2zonzts6N87bOkfO2zpXzts6Z87bOnfO2zqHzts6l87bOqfO2zq3zts6x87bOtfO2zrnzts6987bOwfO2zsXzts7J87bOzfO2ztHzts7V87bO2fO2zt3zts7h87bO5fO2zunzts7t87bO8fO2zvXzts7587bO/fO20gHzttIF87bSCfO20g3zttIR87bSFfO20hnzttId87bSIfO20iXzttIp87bSLfO20jHzttI187bSOfO20j3zttJB87bSRfO20knzttJN87bSUfO20lXzttJZ87bSXfO20mHzttJl87bSafO20m3zttJx87bSdfO20nnzttJ987bQgfO20oXzttKJ87bSjfO20pHzttKV87bSmfO20p3zttKh87bSpfO20qnzttKt87bSsfO20rXzttK587bSvfO20sHzttLF87bSyfO20s3zttLR87bS1fO20tnzttLd87bS4fO20uXzttLp87bS7fO20vHzttL187bS+fO20v3zttYB87bWBfO21gnzttYN87bWEfO21hXzttYZ87bWHfO21iHzttYl87bWKfO21i3zttYx87bWNfO21jnzttY987bWQfO21kXzttZJ87bWTfO21lHzttZV87bWWfO21l3zttZh87bWZfO21mnzttZt87bWcfO21nXzttZ587bWffO21IHzttaF87bWifO21o3zttaR87bWlfO21pnzttad87bWofO21qXzttap87bWrfO21rHztta187bWufO21r3zttbB87bWxfO21snzttbN87bW0fO21tXzttbZ87bW3fO21uHzttbl87bW6fO21u3zttbx87bW9fO21vnzttb987baAfO22gXzttoJ87baDfO22hHzttoV87baGfO22h3zttoh87baJfO22inzttot87baMfO22jXztto587baPfO22kHzttpF87baSfO22k3zttpR87baVfO22lnzttpd87baYfO22mXzttpp87babfO22nHzttp187baefO22n3zttiB87bahfO22onzttqN87bakfO22pXzttqZ87banfO22qHzttql87baqfO22q3zttqx87batfO22rnzttq987bawfO22sXzttrJ87bazfO22tHzttrV87ba2fO22t3zttrh87ba5fO22unzttrt87ba8fO22vXzttr587ba/fO23gHztt4F87beCfO23g3ztt4R87beFfO23hnztt4d87beIfO23iXztt4p87beLfO23jHztt4187beOfO23j3ztt5B87beRfO23knztt5N87beUfO23lXztt5Z87beXfO23mHztt5l87beafO23m3ztt5x87bedfO23nnztt5987bcgfO23oXztt6J87bejfO23pHztt6V87bemfO23p3ztt6h87bepfO23qnztt6t87besfO23rXztt6587bevfO23sHztt7F87beyfO23s3ztt7R87be1fO23tnztt7d87be4fO23uXztt7p87be7fO23vHztt7187be+fO23v3ztuIB87biBfO24gnztuIN87biEfO24hXztuIZ87biHfO24iHztuIl87biKfO24i3ztuIx87biNfO24jnztuI987biQfO24kXztuJJ87biTfO24lHztuJV87biWfO24l3ztuJh87biZfO24mnztuJt87bicfO24nXztuJ587biffO24IHztuKF87biifO24o3ztuKR87bilfO24pnztuKd87biofO24qXztuKp87birfO24rHztuK187biufO24r3ztuLB87bixfO24snztuLN87bi0fO24tXztuLZ87bi3fO24uHztuLl87bi6fO24u3ztuLx87bi9fO24vnztuL987bmAfO25gXztuYJ87bmDfO25hHztuYV87bmGfO25h3ztuYh87bmJfO25inztuYt87bmMfO25jXztuY587bmPfO25kHztuZF87bmSfO25k3ztuZR87bmVfO25lnztuZd87bmYfO25mXztuZp87bmbfO25nHztuZ187bmefO25n3ztuSB87bmhfO25onztuaN87bmkfO25pXztuaZ87bmnfO25qHztual87bmqfO25q3ztuax87bmtfO25rnztua987bmwfO25sXztubJ87bmzfO25tHztubV87bm2fO25t3ztubh87bm5fO25unztubt87bm8fO25vXztub587bm/fO26gHztuoF87bqCfO26g3ztuoR87bqFfO26hnztuod87bqIfO26iXztuop87bqLfO26jHztuo187bqOfO26j3ztupB87bqRfO26knztupN87bqUfO26lXztupZ87bqXfO26mHztupl87bqafO26m3ztupx87bqdfO26nnztup987bogfO26oXztuqJ87bqjfO26pHztuqV87bqmfO26p3ztuqh87bqpfO26qnztuqt87bqsfO26rXztuq587bqvfO26sHzturF87bqyfO26s3zturR87bq1fO26tnzturd87bq4fO26uXzturp87bq7fO26vHztur187bq+fO26v3ztu4B87buBfO27gnztu4N87buEfO27hXztu4Z87buHfO27iHztu4l87buKfO27i3ztu4x87buNfO27jnztu4987buQfO27kXztu5J87buTfO27lHztu5V87buWfO27l3ztu5h87buZfO27mnztu5t87bucfO27nXztu5587buffO27IHztu6F87buifO27o3ztu6R87bulfO27pnztu6d87buofO27qXztu6p87burfO27rHztu6187buufO27r3ztu7B87buxfO27snztu7N87bu0fO27tXztu7Z87bu3fO27uHztu7l87bu6fO27u3ztu7x87bu9fO27vnztu7987byAfO28gXztvIJ87byDfO28hHztvIV87byGfO28h3ztvIh87byJfO28inztvIt87byMfO28jXztvI587byPfO28kHztvJF87bySfO28k3ztvJR87byVfO28lnztvJd87byYfO28mXztvJp87bybfO28nHztvJ187byefO28n3ztvCB87byhfO28onztvKN87bykfO28pXztvKZ87bynfO28qHztvKl87byqfO28q3ztvKx87bytfO28rnztvK987bywfO28sXztvLJ87byzfO28tHztvLV87by2fO28t3ztvLh87by5fO28unztvLt87by8fO28vXztvL587by/fO29gHztvYF87b2CfO29g3ztvYR87b2FfO29hnztvYd87b2IfO29iXztvYp87b2LfO29jHztvY187b2OfO29j3ztvZB87b2RfO29knztvZN87b2UfO29lXztvZZ87b2XfO29mHztvZl87b2afO29m3ztvZx87b2dfO29nnztvZ987b0gfO29oXztvaJ87b2jfO29pHztvaV87b2mfO29p3ztvah87b2pfO29qnztvat87b2sfO29rXztva587b2vfO29sHztvbF87b2yfO29s3ztvbR87b21fO29tnztvbd87b24fO29uXztvbp87b27fO29vHztvb187b2+fO29v3ztvoB87b6BfO2+gnztvoN87b6EfO2+hXztvoZ87b6HfO2+iHztvol87b6KfO2+i3ztvox87b6NfO2+jnztvo987b6QfO2+kXztvpJ87b6TfO2+lHztvpV87b6WfO2+l3ztvph87b6ZfO2+mnztvpt87b6cfO2+nXztvp587b6ffO2+IHztvqF87b6ifO2+o3ztvqR87b6lfO2+pnztvqd87b6ofO2+qXztvqp87b6rfO2+rHztvq187b6ufO2+r3ztvrB87b6xfO2+snztvrN87b60fO2+tXztvrZ87b63fO2+uHztvrl87b66fO2+u3ztvrx87b69fO2+vnztvr987b+AfO2/gXztv4J87b+DfO2/hHztv4V87b+GfO2/h3ztv4h87b+JfO2/inztv4t87b+MfO2/jXztv4587b+PfO2/kHztv5F87b+SfO2/k3ztv5R87b+VfO2/lnztv5d87b+YfO2/mXztv5p87b+bfO2/nHztv5187b+efO2/n3ztvyB87b+hfO2/onztv6N87b+kfO2/pXztv6Z87b+nfO2/qHztv6l87b+qfO2/q3ztv6x87b+tfO2/rnztv6987b+wfO2/sXztv7J87b+zfO2/tHztv7V87b+2fO2/t3ztv7h87b+5fO2/unztv7t87b+8fO2/vXztv7587b+/fO+/vnzvv78=";

		return ereg_replace(base64_decode($_eregreplacedata), "", $_data);
	}

	/**
	* Create a Staff Reply
	*/
	function createStaffReply($staffid, $fullname, $email, $subject, $contents, $isemailed, $fromemailqueueid, $attachments, $cc, $ccaddrecp, $bcc, $bccaddrecp, $downloadlink = false, $ismobile = false, $dontsendemail = false)
	{
		global $dbCore, $_SWIFT, $template, $module;

		if (!$this->ticket)
		{
			return false;
		}

		if (empty($_SWIFT["staff"]["staffid"]))
		{
			$_SWIFT["ruleignorestaffid"] = $staffid;
		}

		if (!empty($cc))
		{
			if (strstr($cc, ","))
			{
				$ccemaillist = explode(",", $cc);
			} else if (isValidEmail($cc)) {
				$ccemaillist = array($cc);
			}
			if ($ccaddrecp == true)
			{
				$this->addRecipients($ccemaillist, RECIPIENT_CCUSER);
			}
		}

		if (!empty($bcc))
		{
			if (strstr($bcc, ","))
			{
				$bccemaillist = explode(",", $bcc);
			} else if (isValidEmail($bcc)) {
				$bccemaillist = array($bcc);
			}
			if ($bccaddrecp == true)
			{
				$this->addRecipients($bccemaillist, RECIPIENT_BCCUSER);
			}
		}

		$queuesignature = $_SWIFT["queuecache"]["list"][$fromemailqueueid]["contents"];
		$staffsignature = $_SWIFT["staff"]["signature"];
		$contents = preg_replace("#(\r\n|\r|\n)#s", SWIFT_CRLF, $contents).iif(!empty($staffsignature), SWIFT_CRLF.$staffsignature, iif(!empty($queuesignature), SWIFT_CRLF.$queuesignature));
		// This one creates the post in database
		$ticketpostresult = $this->createTicketPost(false, POST_STAFF, 0, $staffid, $fullname, $email, "", $subject, $contents, false, $isemailed, $attachments);
		$ticketpostid = $ticketpostresult[0];

		// Now we get other recipients that might be current assigned to this ticket
		$_recipients = $this->getRecipients();

		// For now we will only send mails to CC'ed and BCC users. not to third parties.
		// Build CC Mail List
		$_ccmaillist = $_bccmaillist = $_thirdpartylist = array();
		foreach ($_recipients as $key=>$val)
		{
			if ($val["recipienttype"] == RECIPIENT_CCUSER)
			{
				$_ccmaillist[] = $val["email"];
			} else if ($val["recipienttype"] == RECIPIENT_BCCUSER) {
				$_bccmaillist[] = $val["email"];
			} else if ($val["recipienttype"] == RECIPIENT_THIRDPARTY) {
				$_thirdpartylist[] = $val["email"];
			}
		}


		if (count($ccemaillist))
		{
			foreach ($ccemaillist as $key=>$val)
			{
				if (!in_array($val, $_ccmaillist) && isValidEmail($val))
				{
					$_ccmaillist[] = $val;
				}
			}
		}
		if (count($bccemaillist))
		{
			foreach ($bccemaillist as $key=>$val)
			{
				if (!in_array($val, $_bccmaillist) && isValidEmail($val))
				{
					$_bccmaillist[] = $val;
				}
			}
		}
		//Mahesh Slaria
		require_once ("./includes/functions_mail.php");
		$mailObj = new SWIFT_Mail();
		$_templateattachments = array();

		$hasattachments = $this->processPostAttachments($ticketpostid, $downloadlink, $mailObj, $_templateattachments);
		$template->assign("postattachments", $_templateattachments);
		if (($isemailed || $ismobile) && count($attachments))
		{
			foreach ($attachments as $key=>$val)
			{
				$mailObj->addAttachment(iif(!empty($val["data"]), $val["data"], $val["contents"]), $val["filename"], iif(!empty($val["contenttype"]), $val["contenttype"], 'application/octet-stream'));
			}
		}

		// See if tgroupid is set?
		$template->setGroup(iif(empty($this->ticket["tgroupid"]), 1, $this->ticket["tgroupid"]));
		$template->loadLanguageSection("default", TEMPLATE_DB);
		$template->loadLanguageSection("ticketemails", TEMPLATE_DB);

		$this->loadTemplateVariables();

		if ($_SWIFT["settings"]["t_postlist"] == 1 || $_SWIFT["settings"]["t_enhistory"] == 1)
		{
			$template->assign("postlist", $this->getTicketPosts(false, false, iif($_SWIFT["settings"]["t_cpostorder"]=="asc", "asc", "desc"), true));
		}
		$template->assign("contentshtml", iif($_SWIFT["settings"]["t_chtml"]==1, nl2br(htmlspecialchars($contents)), getProcessedHTML($contents)));
		$template->assign("contentstext", $contents);
		$template->assign("ishtml", true);
		$_templateresulthtml = $template->displayTemplate("email_staffreply", TEMPLATE_DB);
		$template->assign("ishtml", false);
		$_templateresulttext = $template->displayTemplate("email_staffreply", TEMPLATE_DB);
		//require_once ("./includes/functions_mail.php");
		//$mailObj = new SWIFT_Mail();

		if ($ismobile && count($attachments))
		{
/*			require_once ("./modules/tickets/functions_attachments.php");
			$_attach = new TicketAttachments();
			foreach ($attachments as $key=>$val)
			{
				$_attach->dataToChunks($this->ticket["ticketid"], $ticketpostid, $val["filename"], $val["filesize"], $val["contenttype"], $val["contents"]);
			}*/
		}

		if (!empty($ticketpostresult[1]))
		{
			$messageid = sprintf('<%s@%s>', $ticketpostresult[1], $mailObj->getLocalHost());
			$mailObj->setHeader("Message-ID", $messageid);
		}

		$mailObj->setSubject($this->getEmailSubject(SUBJECT_USER));
		$mailObj->setData($_templateresulthtml, $_templateresulttext);

		if (!$dontsendemail)
		{
			$returnemail = $this->getReturnEmail($fromemailqueueid);
			$returnname = $this->getReturnName($fromemailqueueid);
			if (empty($this->ticket["email"]) && count($_ccmaillist))
			{
				$mailObj->sendMail($_ccmaillist, $returnemail, $returnname, false);
			} else if (!empty($this->ticket["email"])) {
				$mailObj->setCC(implode(",", $_ccmaillist));
				$mailObj->sendMail($this->ticket["email"], $returnemail, $returnname, false);
			}
			if (_is_array($_bccmaillist))
			{
				$mailObj->sendMail($_bccmaillist, $returnemail, $returnname, false);
			}
			if (count($_thirdpartylist))
			{
				unset($mailObj->headers['Cc']);
				unset($mailObj->headers['Bcc']);
				$mailObj->setSubject($this->getEmailSubject(SUBJECT_THIRDPARTY));
				$mailObj->sendMail($_thirdpartylist, $returnemail, $returnname, false);
			}
		}

		return $ticketpostid;
	}

	/**
	* Get a single ticket post
	*/
	function getTicketPost($ticketpostid)
	{
		global $dbCore;

		if (!$this->ticket)
		{
			return false;
		}

		$_ticketpost = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."ticketposts` WHERE `ticketpostid` = '". intval($ticketpostid) ."';");
		if ($_ticketpost["ticketid"] != $this->ticket["ticketid"])
		{
			return false;
		}

		return $_ticketpost;
	}

	/**
	* Added later to fix Message ID Issues with PHP CLI
	*/
	function getLocalHost() 
	{ 
		if (!empty($_SERVER['HTTP_HOST']))
		{
			return $_SERVER['HTTP_HOST'];
		}

		if (!empty($_SERVER['SERVER_NAME']))
		{
			return $_SERVER['SERVER_NAME'];
		}

		if (!empty($_SERVER['HOST']))
		{
			return $_SERVER['HOST'];;
		}

		return "localhost";
	}

	/**
	* Generates a Random Message ID
	*/
	function generateRandomMessageID()
	{
		srand((double)microtime()*10000000);
		$messageid = base_convert(time(), 10, 36).".". base_convert(rand(), 10, 36);
		return $messageid;
	}

	/**
	* Insert a Unique Message ID into the list
	*/
	function insertTicketMessageID($ticketpostid)
	{
		global $dbCore;

		if (!$this->ticket)
		{
			return false;
		}

		$messageid = $this->generateRandomMessageID();

		$dbCore->query("INSERT INTO `". TABLE_PREFIX ."ticketmessageids` (`messageid`, `ticketid`, `ticketpostid`, `dateline`) VALUES ('". $dbCore->escape($messageid) ."', '". intval($this->ticket["ticketid"]) ."', '". intval($ticketpostid) ."', '". DATENOW ."');");
		$ticketmessageid = $dbCore->lastInsertId();

		return array($messageid, $ticketmessageid);
	}

	/**
	* Creates a new Ticket Post
	*/
	function createTicketPost($isnewticket, $posttype, $userid, $staffid, $fullname, $email, $emailto, $subject, $contents, $ishtml, $isemailed = false, $attachments = false)
	{
		global $dbCore, $_SWIFT, $template;

		$dbCore->query("INSERT INTO `". TABLE_PREFIX ."ticketposts` (`ticketid`, `dateline`, `userid`, `fullname`, `email`, `emailto`, `subject`, `ipaddress`, `hasattachments`, `edited`, `editedbystaffid`, `editeddateline`, `creator`, `ishtml`, `isemailed`, `staffid`, `contents`, `contenthash`, `subjecthash`) VALUES ('". intval($this->ticketid) ."', '". DATENOW ."', '". intval($userid) ."', '". $dbCore->escape($this->filterJunkCharacters($fullname)) ."', '". $dbCore->escape($this->filterJunkCharacters($email)) ."', '". $dbCore->escape($emailto) ."', '". $dbCore->escape($this->filterJunkCharacters($subject)) ."', '". $dbCore->escape(iif(SWIFT_AREA!=SWIFT_CRON,$_SERVER["REMOTE_ADDR"])) ."', '0', '0', '0', '0', '". intval($posttype) ."', '". intval($ishtml) ."', '". intval($isemailed) ."', '". intval($staffid) ."', '". $dbCore->escape($this->filterJunkCharacters($contents)) ."', '". md5($contents) ."', '". md5($subject) ."');");
		$ticketpostid = $dbCore->lastInsertId();
		if (!$ticketpostid)
		{
			return false;
		}

		$this->ticket["lastpostid"] = intval($ticketpostid);
		$this->updatesql[] = "`lastpostid` = '". intval($ticketpostid) ."'";
		$this->updatesql[] = "`lastactivity` = '". DATENOW ."'";
		$this->updatesql[] = "`lastreplier` = '". $dbCore->escape($fullname) ."'";

		buildTicketPostIndex($ticketpostid, $contents, $subject);

		$this->recount[] = $this->ticket["departmentid"];

		// ======= MESSAGE ID STUFF =======
		$messageidarray = $this->insertTicketMessageID($ticketpostid);
		$messageid = $messageidarray[0];
		$ticketmessageid = $messageidarray[1];
		if ($isnewticket == true)
		{
			$this->setMessageID($messageid);
		}

		// Process all the Ticket Attachments
		$hasattachments = false;
		if (_is_array($attachments))
		{
			require_once ("./modules/tickets/functions_attachments.php");
			$_attach = new TicketAttachments();
			foreach ($attachments as $key=>$val)
			{
				$_attach->dataToChunks($this->ticket["ticketid"], $ticketpostid, $val["filename"], $val["filesize"], $val["contenttype"], $val["contents"]);
				$hasattachments = true;
				unset($val["contents"]);
			}
		}
		if ($hasattachments)
		{
			$this->updatesql[] = "`hasattachments` = '1'";
			$dbCore->shutdownQuery("UPDATE `". TABLE_PREFIX ."ticketposts` SET `hasattachments` = '1' WHERE `ticketpostid` = '". intval($ticketpostid) ."'");
		}

		if ($posttype == POST_STAFF)
		{
			$template->assign("replytype", "staff");
			if ($_SWIFT["settings"]["t_slaresets"] == 1)
			{
				$this->clearDue();
			}
			$this->clearDraft();
			$this->updatesql[] = "`laststaffreplytime` = '". DATENOW ."'";
			$this->addAuditLogEntry($this->logtype, ACTION_NEWREPLY, sprintf(iif(!empty($emailto), $_SWIFT["language"]["al_newforward"], $_SWIFT["language"]["al_newreply"]), htmlspecialchars($fullname), htmlspecialchars($email)));

			// Send the outgoing email to client.

		} else if (!$isnewticket) {
			$template->assign("replytype", "user");
			$this->resetTemplateGroupStatus();
			$this->addAuditLogEntry(LOG_CLIENT, ACTION_NEWREPLY, sprintf($_SWIFT["language"]["al_newreply"], htmlspecialchars($fullname), htmlspecialchars($email)));
		}

		if (($posttype == POST_CLIENT || $posttype == POST_RECIPIENT || $posttype == POST_THIRDPARTY) && !empty($_SWIFT["settings"]["t_cstatusupd"]) && !$isnewticket)
		{
			$this->changeStatus($_SWIFT["settings"]["t_cstatusupd"]);
			$this->resetsla = true;
		}

		if ($posttype == POST_CLIENT)
		{
			$this->updatesql[] = "`lastuserreplytime` = '". DATENOW ."'";
		}

		$this->updateTicketCount();

		if ($isnewticket != true)
		{
			if ($isemailed && $ishtml)
			{
				$alertcontents = strip_tags(str_replace("<br />", "\n", str_replace("<BR />", "\n", $contents)));
			} else {
				$alertcontents = $contents;
			}
//			$this->updatesql[] = "`totalreplies` = `totalreplies`+1";
			$this->alerts->addAttachments($attachments);
			$this->alerts->raiseAlert(iif($posttype==POST_STAFF, ALERT_NEWSTAFFREPLY, ALERT_NEWREPLY), array("contentshtml" => getProcessedHTML($contents), "contentstext" => getProcessedText($alertcontents), "contentssms" => substr(getProcessedText($contents),0,40), "fullname" => $fullname));
		}

		return array($ticketpostid, $messageid);
	}

	/**
	* Add a ticket note
	*/
	function addTicketNote($notetype, $forstaffid, $notes)
	{
		global $dbCore, $_SWIFT;

		if ($notetype == NOTE_TICKET)
		{
			$typeid = $this->ticket["ticketid"];
		} else if ($notetype == NOTE_USER) {
			$typeid = $this->ticket["userid"];
		}

		$dbCore->shutdownQuery("INSERT INTO `". TABLE_PREFIX ."ticketnotes` (`typeid`, `notetype`, `forstaffid`, `bystaffid`, `dateline`, `notes`) VALUES ('". intval($typeid) ."', '". intval($notetype) ."', '". intval($forstaffid) ."', '". intval($_SWIFT["staff"]["staffid"]) ."', '". DATENOW ."', '". $dbCore->escape($notes) ."');");

		$this->updatesql[] = "`hasnotes` = '1'";
		$this->updatesql[] = "`lastactivity` = '". DATENOW ."'";

		$this->alerts->raiseAlert(ALERT_NOTE, array("notetype" => iif($notetype==NOTE_TICKET, "ticket", "user"), "staffid" => $_SWIFT["staff"]["staffid"], "bystaff" => $_SWIFT["staff"]["fullname"], "forstaff" => $_SWIFT["staffcache"][$forstaffid]["fullname"], "forstaffid" => $forstaffid, "contentshtml" => getProcessedHTML($notes), "contentstext" => getProcessedText($notes), "contentssms" => substr(getProcessedText($notes),0,40)));

		if (empty($_SWIFT["staff"]["fullname"]))
		{
			$userfullname = $_SWIFT["language"]["alsystem"];
		} else {
			$userfullname = $_SWIFT["staff"]["fullname"];
		}

		if ($notetype == NOTE_TICKET)
		{
			$this->addAuditLogEntry($this->logtype, ACTION_TICKETNOTE, sprintf($_SWIFT["language"]["al_ticketnote"], htmlspecialchars($userfullname)));
		} else if ($notetype == NOTE_USER) {
			$this->addAuditLogEntry($this->logtype, ACTION_USERNOTE, sprintf($_SWIFT["language"]["al_usernote"], htmlspecialchars($userfullname)));
		}

		return true;
	}

	/**
	* Delete the given ticket note.
	*/
	function deleteTicketNote($ticketnoteid)
	{
		global $dbCore, $_SWIFT;

		// First get the ticket note
		$_ticketnote = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."ticketnotes` WHERE `ticketnoteid` = '". intval($ticketnoteid) ."';");
		if (!empty($_ticketnote))
		{
			$dbCore->query("DELETE FROM `". TABLE_PREFIX ."ticketnotes` WHERE `ticketnoteid` = '". intval($ticketnoteid) ."';");

			// Has Notes?
			$_hasnotes = $dbCore->queryFetch("SELECT COUNT(*) AS totalnotes FROM `". TABLE_PREFIX ."ticketnotes` WHERE `typeid` = '". intval($this->ticket["ticketid"]) ."' AND `notetype` = '". NOTE_TICKET ."';");
			$this->updatesql[] = "`hasnotes` = '". iif($_hasnotes["totalnotes"]>0, "1", "0") ."'";

			$this->addAuditLogEntry($this->logtype, ACTION_DELETENOTE, sprintf($_SWIFT["language"]["al_deletenote"], htmlspecialchars($_SWIFT["staff"]["fullname"])));
		}
	}

	/**
	* Change Priority for the Ticket
	*/
	function changePriority($priorityid)
	{
		global $dbCore, $_SWIFT;

		if (!$this->ticket)
		{
			return false;
		}

		if ($this->ticket["priorityid"] == $priorityid)
		{
			return true;
		}

		$this->addAuditLogEntry($this->logtype, ACTION_PRIORITY, sprintf($_SWIFT["language"]["al_priority"], $_SWIFT["prioritycache"][$this->ticket["priorityid"]]["title"], $_SWIFT["prioritycache"][$priorityid]["title"]));

		$this->updatesql[] = "`priorityid` = '". intval($priorityid) ."'";

		$this->alerts->raiseAlert(ALERT_PRIORITY, array("oldpriorityid" => $this->ticket["priorityid"], "newpriorityid" => $priorityid, "oldpriority" => $_SWIFT["prioritycache"][$this->ticket["priorityid"]]["title"], "newpriority" => $_SWIFT["prioritycache"][$priorityid]["title"], "newprioritycolor" => $_SWIFT["prioritycache"][$priorityid]["frcolorcode"], "oldprioritycolor" => $_SWIFT["prioritycache"][$this->ticket["priorityid"]]["frcolorcode"]));

		$this->ticket["priorityid"] = $priorityid;
		$this->resetsla = true;

		return true;
	}

	/**
	* Locks the Ticket to given staff member
	*/
	function lockTicket($staffid)
	{
		global $dbCore, $_SWIFT;

		if ($_SWIFT["settings"]["t_entlock"] != 1 || !$this->ticket)
		{
			return false;
		}

		$dbCore->query("REPLACE INTO `". TABLE_PREFIX ."ticketlocks` (`ticketid`, `lockstaffid`, `lockdateline`) VALUES ('". intval($this->ticket["ticketid"]) ."', '". intval($staffid) ."', '". DATENOW ."');");

		return true;
	}

	/**
	* Change Status for the given ticket
	*/
	function changeStatus($ticketstatusid, $isautoclose = false)
	{
		global $dbCore, $_SWIFT;
	
		if (SWIFT_AREA == SWIFT_CLIENT)
		{
			$this->logtype = LOG_CLIENT;
		}

		if (!$this->ticket)
		{
			return false;
		}

		if ($this->ticket["ticketstatusid"] == $ticketstatusid || $this->duetimecleared == true)
		{
			$this->updatesql[] = "`ticketstatusid` = '". intval($ticketstatusid) ."'";
			return true;
		}

		if ($isautoclose == true)
		{
			$this->addAuditLogEntry($this->logtype, ACTION_STATUS, sprintf($_SWIFT["language"]["al_statusac"], $_SWIFT["statuscache"][$this->ticket["ticketstatusid"]]["title"], $_SWIFT["statuscache"][$ticketstatusid]["title"]));
			$this->updatesql[] = "`autoclosetimeline` = '0'";
		} else {
			$this->addAuditLogEntry($this->logtype, ACTION_STATUS, sprintf($_SWIFT["language"]["al_status"], $_SWIFT["statuscache"][$this->ticket["ticketstatusid"]]["title"], $_SWIFT["statuscache"][$ticketstatusid]["title"]));
		}


		$this->updatesql[] = "`ticketstatusid` = '". intval($ticketstatusid) ."'";

		// REMOVED: VARUN
//		if ( $_SWIFT["statuscache"][$ticketstatusid]["ticketstatusid"] == STATUS_CLOSED)
//		{
//			$this->clearDue(); //clear the Due date after ticket closed.
//		}
		
		$this->recount[] = $this->ticket["departmentid"];

		$this->alerts->raiseAlert(ALERT_STATUS, array("oldticketstatusid" => $this->ticket["ticketstatusid"], "newticketstatusid" => $ticketstatusid, "oldticketstatus" => $_SWIFT["statuscache"][$this->ticket["ticketstatusid"]]["title"], "newticketstatus" => $_SWIFT["statuscache"][$ticketstatusid]["title"], "newstatuscolor" => $_SWIFT["statuscache"][$ticketstatusid]["statuscolor"], "oldstatuscolor" => $_SWIFT["statuscache"][$this->ticket["ticketstatusid"]]["statuscolor"]));

		$this->ticket["ticketstatusid"] = $ticketstatusid;
		
		if ($_SWIFT["statuscache"][$ticketstatusid]["resetduetime"] == "1")
		{
			$this->clearDue();
		}else {
			$this->resetsla = true;
		}
		return true;
	}

	/**
	* Assign a ticket to staff
	*/
	function assignTicket($staffid)
	{
		global $dbCore, $_SWIFT;

		if (!$this->ticket)
		{
			return false;
		}

		if ($this->ticket["ownerstaffid"] == $staffid)
		{
			return true;
		}

		$currentowner = htmlspecialchars($_SWIFT["staffcache"][$this->ticket["ownerstaffid"]]["fullname"]);
		$newowner = htmlspecialchars($_SWIFT["staffcache"][$staffid]["fullname"]);

		$this->addAuditLogEntry($this->logtype, ACTION_ASSIGN, sprintf($_SWIFT["language"]["al_owner"], iif(empty($this->ticket["ownerstaffid"]), $_SWIFT["language"]["unassigned"], $currentowner), iif(empty($staffid), $_SWIFT["language"]["unassigned"], $newowner)));

		$this->updatesql[] = "`ownerstaffid` = '". intval($staffid) ."'";
		if (!$staffid)
		{
			$this->updatesql[] = "`assignstatus` = '0'";
		} else {
			$this->updatesql[] = "`assignstatus` = '1'";
		}

		if ($_SWIFT["staff"]["staffid"] != $staffid)
		{
			$this->alerts->raiseAlert(ALERT_ASSIGN, array("bystaffid" => $this->ticket["staffid"], "bystaff" => $_SWIFT["staff"]["fullname"], "newownerstaffid" => $staffid, "oldownerstaffid" => $this->ticket["ownerstaffid"], "newownerstaff" => $_SWIFT["staffcache"][$staffid]["fullname"], "oldownerstaff" => $_SWIFT["staffcache"][$this->ticket["ownerstaffid"]]["fullname"]));
		}

		$this->ticket["ownerstaffid"] = $staffid;

		return true;
	}

	/**
	* Move ticket to different department
	*/
	function moveTicket($departmentid)
	{
		global $dbCore, $_SWIFT;

		if (!$this->ticket)
		{
			return false;
		}

		if ($this->ticket["departmentid"] == $departmentid)
		{
			return true;
		}

		$this->addAuditLogEntry($this->logtype, ACTION_MOVE, sprintf($_SWIFT["language"]["al_department"], $_SWIFT["departmentcache"][$this->ticket["departmentid"]]["title"], $_SWIFT["departmentcache"][$departmentid]["title"]));

		$this->recount[] = $this->ticket["departmentid"];
		$this->updatesql[] = "`departmentid` = '". intval($departmentid) ."'";
		$this->recount[] = $departmentid;

		$this->alerts->raiseAlert(ALERT_MOVE, array("olddepartmentid" => $this->ticket["departmentid"], "newdepartmentid" => $departmentid, "olddepartment" => $_SWIFT["departmentcache"][$this->ticket["departmentid"]]["title"], "newdepartment" => $_SWIFT["departmentcache"][$departmentid]["title"]));

		$this->ticket["departmentid"] = $departmentid;

		$this->resetsla = true;

		return true;
	}

	/**
	* Returns the Ticket ID For previous ticket in same department
	*/
	function getPreviousTicketID()
	{
		global $dbCore;

		$_ticket = $dbCore->queryFetch("SELECT `ticketid` FROM `". TABLE_PREFIX ."tickets` WHERE `departmentid` = '". intval($this->ticket["departmentid"]) ."' AND `ticketstatusid` = '". intval($this->ticket["ticketstatusid"]) ."' AND `ticketid` < '". intval($this->ticket["ticketid"]) ."' ORDER BY `ticketid` DESC LIMIT 1;");
		if (!empty($_ticket["ticketid"]))
		{
			return intval($_ticket["ticketid"]);
		}

		return false;
	}

	/**
	* Returns the Ticket ID For next ticket in same department
	*/
	function getNextTicketID()
	{
		global $dbCore;

		$_ticket = $dbCore->queryFetch("SELECT `ticketid` FROM `". TABLE_PREFIX ."tickets` WHERE `departmentid` = '". intval($this->ticket["departmentid"]) ."' AND `ticketstatusid` = '". intval($this->ticket["ticketstatusid"]) ."' AND `ticketid` > '". intval($this->ticket["ticketid"]) ."' ORDER BY `ticketid` ASC LIMIT 1;");
		if (!empty($_ticket["ticketid"]))
		{
			return intval($_ticket["ticketid"]);
		}

		return false;
	}

	/**
	* Loads the template variables
	*/
	function loadTemplateVariables($issupportcenter = false)
	{
		global $template, $_SWIFT, $dbCore;
		$_ticket = $this->ticket;
		$_ticket["priority"] = $_SWIFT["prioritycache"][$_ticket["priorityid"]]["title"];
		$_ticket["department"] = $_SWIFT["departmentcache"][$_ticket["departmentid"]]["title"];
		$_ticket["status"] = $_SWIFT["statuscache"][$_ticket["ticketstatusid"]]["title"];
		$_ticket["emailqueue"] = $_SWIFT["queuecache"][$_ticket["emailqueueid"]]["email"];
		$_ticket["tgroup"] = $_SWIFT["tgroupcache"][$_ticket["tgroupid"]]["title"];
		$_ticket["ccreatedon"] = edate($_SWIFT["settings"]["dt_datetimeformat"], $_ticket["dateline"]);
		$_ticket["clastupdate"] = edate($_SWIFT["settings"]["dt_datetimeformat"], $_ticket["lastactivity"]);
		$_ticket["staff"] = $_SWIFT["staffcache"][$_ticket["ownerstaffid"]]["fullname"];

		if (empty($_ticket["tgroup"]))
		{
			$_ticket["tgroup"] = "default";
		}

		$template->assign("ticket", $_ticket);
		$template->assign("priority", $_SWIFT["prioritycache"][$_ticket["priorityid"]]);
		$template->assign("status", $_SWIFT["statuscache"][$_ticket["ticketstatusid"]]);
		$template->assign("department", $_SWIFT["departmentcache"][$_ticket["departmentid"]]);
		$template->assign("emailqueue", $_SWIFT["queuecache"][$_ticket["emailqueueid"]]);
		$template->assign("tgroup", $_SWIFT["tgroupcache"][$_ticket["tgroupid"]]);
		$template->assign("staff", $_SWIFT["staffcache"][$_ticket["ownerstaffid"]]);

		// ======= [VARUN] (12/27/2006) TEMPLATE VARIABLE ALLOWING CLIENT TO UPDATE TICKET STATUS =======

		if ($issupportcenter)
		{
			// Ticket Status
			$_ticketstatuslist = $_ticketstatusidlist = array();
			foreach ($_SWIFT["statuscache"] as $key=>$val)
			{
				if ($val["type"] == "public")
				{
					$_ticketstatuslist[$val["ticketstatusid"]] = $val;
					$_ticketstatusidlist[] = $val["ticketstatusid"];
					if ($_ticket["ticketstatusid"] == $val["ticketstatusid"])
					{
						$_ticketstatuslist[$val["ticketstatusid"]]["isselected"] = '1';
					}
				}
			}

			// Perhaps the status the ticket is set to is set as Private? Then we will need to add to the array manually
			if (!in_array($_ticket["ticketstatusid"], $_ticketstatusidlist) && isset($_SWIFT["statuscache"][$_ticket["ticketstatusid"]]))
			{
				$_ticketstatuslist[$_ticket["ticketstatusid"]] = $_SWIFT["statuscache"][$_ticket["ticketstatusid"]];
				$_ticketstatuslist[$_ticket["ticketstatusid"]]["isselected"] = '1';
			}

			$template->assign("propticketstatus", $_ticketstatuslist);

			// Ticket Priorities
			$_prioritylist = $_priorityidlist = array();

			$dbCore->query("SELECT ticketpriorities.* FROM `". TABLE_PREFIX ."ticketpriorities` AS ticketpriorities LEFT JOIN `". TABLE_PREFIX ."tgroupassigns` AS tgroupassigns ON (ticketpriorities.priorityid = tgroupassigns.toassignid AND tgroupassigns.type = '". TGROUP_PRIORITY ."') WHERE tgroupassigns.tgroupid = '". intval($_SWIFT["tgroup"]["tgroupid"]) ."' ORDER BY ticketpriorities.displayorder ASC;");
			while ($dbCore->nextRecord())
			{
				if ($dbCore->Record["type"] == SWIFTPUBLIC)
				{
					$_priorityidlist[] = $dbCore->Record["priorityid"];
					$_prioritylist[$dbCore->Record["priorityid"]] = $dbCore->Record;
					if ($dbCore->Record["priorityid"] == $_ticket["priorityid"])
					{
						$_prioritylist[$dbCore->Record["priorityid"]]["isselected"] = '1';
					}
				}
			}

			if (!in_array($_ticket["priorityid"], $_priorityidlist) && isset($_SWIFT["prioritycache"][$_ticket["priorityid"]]))
			{
				$_prioritylist[$_ticket["priorityid"]] = $_SWIFT["prioritycache"][$_ticket["priorityid"]];
				$_prioritylist[$_ticket["priorityid"]]["isselected"] = '1';
			}

			$template->assign("propticketpriorities", $_prioritylist);
		}

		// ======= END =======
	}

	/**
	* Load the User Variable
	*/
	function loadUserTemplateVariables()
	{
		global $dbCore, $_SWIFT, $template;

		if (!empty($this->ticket["userid"]))
		{
			$_user = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."users` AS users LEFT JOIN `". TABLE_PREFIX ."usergroups` AS usergroups ON (users.usergroupid = usergroups.usergroupid) WHERE users.userid = '". intval($this->ticket["userid"]) ."';");
			$template->assign("user", $_user);
		}
	}

	/**
	* Send the Autoresponder Message for this ticket.
	*/
	function sendAutoResponder()
	{
		global $_SWIFT, $template, $dbCore, $module;

		// See if tgroupid is set?
		$_tgroupid = iif(empty($this->ticket["tgroupid"]), 1, $this->ticket["tgroupid"]);
		$template->setGroup($_tgroupid);
		$template->loadLanguageSection("ticketemails", TEMPLATE_DB);

		$this->loadTemplateVariables();
		$this->loadUserTemplateVariables();

		// Load News if necessary
		$_news = array();
		if ($_SWIFT["settings"]["t_arnews"] == 1 && $module->isRegistered(MODULE_NEWS))
		{
			$maxnewsitems = intval($_SWIFT["settings"]["nw_maxnewslist"]);
			if (empty($maxnewsitems))
			{
				$maxnewsitems = $_SWIFT["settings"]["nw_maxnewslist"] = 6;
			}

			$index = 1;
			$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."news` AS news LEFT JOIN `". TABLE_PREFIX ."newsdata` AS newsdata ON (news.newsid = newsdata.newsid) WHERE news.tgroupid = '". intval($_tgroupid) ."' AND news.newstype = '". SWIFTPUBLIC ."' AND (news.expiry > '". DATENOW ."' OR news.expiry = '0') ORDER BY news.newsid DESC LIMIT ". intval($maxnewsitems) .";");
			while ($dbCore->nextRecord())
			{
				$_news[$dbCore->Record["newsid"]] = $dbCore->Record;
				$_news[$dbCore->Record["newsid"]]["index"] = $index;
				$index++;
			}
		}
		$template->assign("news", $_news);
		$template->assign("newscount", count($_news));

		$emailqueueid = $this->ticket["emailqueueid"];
		$template->assign("queuesignature", $_SWIFT["queuecache"]["list"][$emailqueueid]["contents"]);
		$template->assign("ishtml", true);
		$_templateresulthtml = $template->displayTemplate("email_autoresponder", TEMPLATE_DB);
		$template->assign("ishtml", false);
		$_templateresulttext = $template->displayTemplate("email_autoresponder", TEMPLATE_DB);

		require_once ("./includes/functions_mail.php");
		$mailObj = new SWIFT_Mail();

		// ======= DO WE NEED TO SET THE MESSAGE ID FOR THIS AUTO RESPONDER? =======
		if (!empty($this->messageid))
		{
			$messageid = sprintf('<%s@%s>', $this->messageid, $this->getLocalHost());
			$mailObj->setHeader("Message-ID", $messageid);
		}

		$mailObj->setSubject($this->getEmailSubject(SUBJECT_USER));
		$mailObj->setData($_templateresulthtml, $_templateresulttext);
		$returnemail = $this->getReturnEmail();
		$returnname = $this->getReturnName();
		$mailObj->sendMail(array($this->ticket["email"]), $returnemail, $returnname, false);

		return true;
	}

	/**
	* Prints the given ticket
	*/
	function printTicket($_ticketpostid = false)
	{
		global $_SWIFT, $template;

		$ticket = $this->ticket;
		$ticket["date"] = edate($_SWIFT["settings"]["dt_datetimeformat"], $ticket["dateline"]);
		$_posts = $this->getTicketPosts(false, false, "asc");
		foreach ($_posts as $key=>$val)
		{
			if (empty($_ticketpostid) || $_ticketpostid == $val["ticketpostid"])
			{
				$_posts[$key]["date"] = sprintf($_SWIFT["language"]["trdate"], edate($_SWIFT["settings"]["dt_datetimeformat"], $val["dateline"]));
				$_posts[$key]["contents"] = $val["contents"];
/*				if ($_SWIFT["settings"]["t_chtml"] == "entities") {
					$_posts[$key]["contents"] = nl2br(htmlspecialchars($val["contents"]));
				} else {
					$_posts[$key]["contents"] = getProcessedHTML($val["contents"]);
				}*/
			} else {
				unset($_posts[$key]);
			}
		}

		$this->addAuditLogEntry($this->logtype, ACTION_PRINT, sprintf($_SWIFT["language"]["al_print"], htmlspecialchars($_SWIFT["staff"]["fullname"])));

		$template->assign("ticket", $ticket);
		$template->assign("posts", $_posts);
		echo $template->displayTemplate("ticketprint.tpl");
	}

	/**
	* Delete a ticket post
	*/
	function deleteTicketPost($ticketpostid)
	{
		global $dbCore, $_SWIFT;
		$_attachmentidlist = array();

		if (!$this->ticket)
		{
			return 0;
		}

		// Make sure this post belongs to this ticket
		$_ticketpost = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."ticketposts` WHERE `ticketpostid` = '". intval($ticketpostid) ."';");
		if ($_ticketpost["ticketid"] != $this->ticket["ticketid"] || empty($_ticketpost["ticketid"]))
		{
			return 0;
		}

		if ($this->ticket["firstpostid"] == $ticketpostid)
		{
			return -1;
		}

		$dbCore->query("DELETE FROM `". TABLE_PREFIX ."ticketposts` WHERE `ticketpostid` = '". intval($ticketpostid) ."';");
		$this->updatesql[] = "`totalreplies` = `totalreplies`- 1";

		$this->alerts->raiseAlert(ALERT_DELETEPOST, array("ticketid" => $this->ticket["ticketid"], "ticketpostid" => $ticketpostid, "ticketpost" => $_ticketpost, "contentshtml" => getProcessedHTML($_ticketpost["contents"]), "contentstext" => getProcessedText($_ticketpost["contents"]), "contentssms" => substr(getProcessedText($_ticketpost["contents"]), 0, 40)));
		$this->addAuditLogEntry($this->logtype, ACTION_DELETETICKETPOST, sprintf($_SWIFT["language"]["al_deleteticketpost"], htmlspecialchars($_SWIFT["staff"]["fullname"])));

		//-----------Mahesh Slaria--------------------->
		$dbCore->query("SELECT `attachmentid` FROM `". TABLE_PREFIX ."attachments` WHERE `ticketpostid` = '". intval($ticketpostid) ."';");
		while ($dbCore->nextRecord())
		{
			$_attachmentidlist[] = $dbCore->Record["attachmentid"];
		}

		if (count($_attachmentidlist))
		{
			$dbCore->query("DELETE FROM `". TABLE_PREFIX ."attachments` WHERE `attachmentid` IN (". buildIN($_attachmentidlist) .");");
		}

		$_countresult = $dbCore->queryFetch("SELECT COUNT(*) AS totalattach FROM `". TABLE_PREFIX ."attachments` WHERE `ticketid` = '". intval($this->ticket["ticketid"]) ."';");

		if ($_countresult["totalattach"] > 0)
		{
			$this->updatesql[] = "`hasattachments` = '1'";
		} else {
			$this->updatesql[] = "`hasattachments` = '0'";
		}
		//--------------------------------------------

		// ======= VARUN SHOOR =======
		// Code to update the last replier when ticket post is deleted.

		$_lastpost = $dbCore->queryFetch("SELECT `ticketpostid`, `fullname` FROM `". TABLE_PREFIX ."ticketposts` WHERE `ticketid` = '". intval($this->ticket["ticketid"]) ."' ORDER BY `ticketpostid` DESC LIMIT 1;");
		$this->updatesql[] = "`lastreplier` = '". $dbCore->escape($_lastpost["fullname"]) ."'";
		$this->updatesql[] = "`lastpostid` = '". $dbCore->escape($_lastpost["ticketpostid"]) ."'";
		// ==============
		return 1;
	}

	/**
	* Recalculates stuff and checks all properties
	*/
	function updateTicketCount()
	{
		global $dbCore;

		if (!$this->ticket)
		{
			return false;
		}

		// First Post, Last Post & Total Replies
		$_count = $dbCore->queryFetch("SELECT COUNT(*) AS totalreplies FROM `". TABLE_PREFIX ."ticketposts` WHERE `ticketid` = '". intval($this->ticket["ticketid"]) ."';");

		if (!empty($_count["totalreplies"]))
		{
			if ($_count["totalreplies"] > 0)
			{
				$_count["totalreplies"]--;
			}
			$this->updatesql[] = "`totalreplies` = '". intval($_count["totalreplies"]) ."'";
		}
	}

	/**
	* Recalculates stuff and checks all properties
	*/
	function updateTicketProperties()
	{
		global $dbCore;

		if (!$this->ticket)
		{
			return false;
		}

		// First Post, Last Post & Total Replies
		$_count = $dbCore->queryFetch("SELECT MIN(ticketpostid) AS firstpostid, MAX(ticketpostid) AS lastpostid, COUNT(*) AS totalreplies FROM `". TABLE_PREFIX ."ticketposts` WHERE `ticketid` = '". intval($this->ticket["ticketid"]) ."';");
		if (!empty($_count["firstpostid"]))
		{
			$this->updatesql[] = "`firstpostid` = '". intval($_count["firstpostid"]) ."'";
		}
		if (!empty($_count["lastpostid"]))
		{
			$this->updatesql[] = "`lastpostid` = '". intval($_count["lastpostid"]) ."'";
			$_lastactivity = $dbCore->queryFetch("SELECT `fullname`, `dateline` FROM `". TABLE_PREFIX ."ticketposts` WHERE `ticketpostid` = '". intval($_count["lastpostid"]) ."';");
			if (!empty($_lastactivity["fullname"]))
			{
				$this->updatesql[] = "`lastreplier` = '". $dbCore->escape($_lastactivity["fullname"]) ."'";
			}
			if ($_lastactivity["dateline"] > $this->ticket["lastactivity"])
			{
				$this->updatesql[] = "`lastactivity` = '". intval($_lastactivity["dateline"]) ."'";
			}
		}
		if (!empty($_count["totalreplies"]))
		{
			if ($_count["totalreplies"] > 0)
			{
				$_count["totalreplies"]--;
			}

			$this->updatesql[] = "`totalreplies` = '". intval($_count["totalreplies"]) ."'";
		}

		// Has Notes?
		$_hasnotes = $dbCore->queryFetch("SELECT COUNT(*) AS totalnotes FROM `". TABLE_PREFIX ."ticketnotes` WHERE `typeid` = '". intval($this->ticket["ticketid"]) ."' AND `notetype` = '". NOTE_TICKET ."';");
		$this->updatesql[] = "`hasnotes` = '". iif($_hasnotes["totalnotes"]>0, "1", "0") ."'";

		// Has Attachments?
		$_hasattachments = $dbCore->queryFetch("SELECT COUNT(*) AS totalattachments FROM `". TABLE_PREFIX ."attachments` WHERE `ticketid` = '". intval($this->ticket["ticketid"]) ."';");
		$this->updatesql[] = "`hasattachments` = '". iif($_hasattachments["totalattachments"]>0, "1", "0") ."'";

		// Has Draft?
		$_hasdraft = $dbCore->queryFetch("SELECT COUNT(*) AS totalitems FROM `". TABLE_PREFIX ."ticketdrafts` WHERE `ticketid` = '". intval($this->ticket["ticketid"]) ."';");
		$this->updatesql[] = "`hasdraft` = '". iif($_hasdraft["totalitems"]>0, "1", "0") ."'";

		/**
		* ###############################################
		* TODO: CALCULATE TIME WORKED
		* ###############################################
		*/

		return true;
	}

	/**
	* Set the ticket messageid
	*/
	function setMessageID($messageid)
	{
		global $dbCore;

		$this->updatesql[] = "`messageid` = '". $dbCore->escape($messageid) ."'";
		$this->ticket["messageid"] = $messageid;
	}

	/**
	* Clears the draft
	*/
	function clearDraft()
	{
		global $dbCore, $_SWIFT;

		if (!$this->ticket || $this->ticket["hasdraft"] != 1)
		{
			return false;
		}

		$this->addAuditLogEntry($this->logtype, ACTION_CLEARDRAFT, sprintf($_SWIFT["language"]["al_cleardraft"], htmlspecialchars($_SWIFT["staff"]["fullname"])));
		$dbCore->query("DELETE FROM `". TABLE_PREFIX ."ticketdrafts` WHERE `ticketid` = '". intval($this->ticket["ticketid"]) ."';");

		$this->updatesql[] = "`hasdraft` = '0'";
	}

	/**
	* Save a draft for this ticket
	*/
	function saveDraft($draftcontents)
	{
		global $dbCore, $_SWIFT;

		if (!$this->ticket)
		{
			return false;
		}

		$this->addAuditLogEntry($this->logtype, ACTION_SAVEDRAFT, sprintf($_SWIFT["language"]["al_savedraft"], htmlspecialchars($_SWIFT["staff"]["fullname"])));
		$dbCore->query("REPLACE INTO `". TABLE_PREFIX ."ticketdrafts` (`ticketid`, `dateline`, `contents`) VALUES ('". intval($this->ticket["ticketid"]) ."', '". DATENOW ."', '". $dbCore->escape($draftcontents) ."');");

		$this->updatesql[] = "`hasdraft` = '1'";
	}

	/**
	* Processes attachments received via post
	*/
	function processPostAttachments($ticketpostid, $downloadlink, &$mailObj, &$_attachmentlist)
	{
		global $_SWIFT, $dbCore, $module, $template;

		$hasattachments = false;
		if (_is_array($_FILES["opt_file"]["name"]))
		{
			$fileindex = 0;
			$_filelist = array();
			foreach ($_FILES["opt_file"]["name"] as $key=>$val)
			{
				if (!empty($val))
				{
					$_filelist[$fileindex]["name"] = $val;
					$_filelist[$fileindex]["type"] = $_FILES["opt_file"]["type"][$key];
					$_filelist[$fileindex]["tmp_name"] = $_FILES["opt_file"]["tmp_name"][$key];
					$_filelist[$fileindex]["error"] = $_FILES["opt_file"]["error"][$key];
					$_filelist[$fileindex]["size"] = $_FILES["opt_file"]["size"][$key];
					$_filelist[$fileindex]["filesize"] = formattedSize($_FILES["opt_file"]["size"][$key]);
					$fileindex++;
				}
			}

			if (is_array($_attachmentlist))
			{
				$_attachmentlist = $_filelist;
			}

			// We have a file to add!
			require_once ("./modules/tickets/functions_attachments.php");
			$_attach = new TicketAttachments();
			if (count($_filelist))
			{
				foreach ($_filelist as $key=>$val)
				{
					if (file_exists($val["tmp_name"]))
					{
						if (is_object($mailObj))
						{
							if (strtolower(get_class($mailObj)) == "swift_mail")
							{
								$mailObj->addAttachment(implode("", file($val["tmp_name"])), $val["name"], iif(!empty($val["type"]), $val["type"], 'application/octet-stream'));
							}
						}
						$_attach->fileToChunks($this->ticket["ticketid"], $ticketpostid, $val["tmp_name"], $val["name"], $val["type"]);
						$hasattachments = true;
					}
				}
			}
			unset($_filelist);
		}

		if (_is_array($downloadlink) && $module->isRegistered(MODULE_DOWNLOADS))
		{
			require_once ("./modules/tickets/functions_attachments.php");
			$_attach = new TicketAttachments();
			$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."downloaditems` WHERE `downloaditemid` IN (". buildIN($downloadlink) .");", 2);
			while ($dbCore->nextRecord(2))
			{
				if (file_exists("./files/".$dbCore->Record2["storedfilename"])) // File Exists?
				{
					// First add as mail attachment
					if (is_object($mailObj))
					{
						$mailObj->addAttachment(implode("", file("./files/".$dbCore->Record2["storedfilename"])), $dbCore->Record2["filename"], iif(!empty($dbCore->Record2["filetype"]), $dbCore->Record2["filetype"], 'application/octet-stream'));
					}
					// Then add to attachments table
					$_attach->addDownloadsAttachment($this->ticket["ticketid"], $ticketpostid, $dbCore->Record2["downloaditemid"], $dbCore->Record2["filename"], $dbCore->Record2["filetype"], $dbCore->Record2["filesize"]);
					$hasattachments = true;
				}
			}
		}

		if ($hasattachments)
		{
			$this->updatesql[] = "`hasattachments` = '1'";
			$dbCore->shutdownQuery("UPDATE `". TABLE_PREFIX ."ticketposts` SET `hasattachments` = '1' WHERE `ticketpostid` = '". intval($ticketpostid) ."'");
		}

		return $hasattachments;
	}

	/**
	* Forward ticket to third party
	*/
	function forwardTicket($staffid, $fullname, $email, $emailto, $subject, $contents, $fromemailqueueid, $addrecipient = false, $downloadlink = false, $_attachmentidlist = array())
	{
		global $dbCore, $_SWIFT, $template, $module;

		if (!$this->ticket)
		{
			return false;
		}

		if (strstr($emailto, ","))
		{
			$emaillist = explode(",", $emailto);
		} else if (isValidEmail($emailto)) {
			$emaillist = array($emailto);
		}
		if ($addrecipient == true)
		{
			$this->addRecipients($emaillist, RECIPIENT_THIRDPARTY);
		}

		$queuesignature = $_SWIFT["queuecache"]["list"][$fromemailqueueid]["contents"];
		$staffsignature = $_SWIFT["staff"]["signature"];
		$contents = preg_replace("#(\r\n|\r|\n)#s", SWIFT_CRLF, $contents).iif(!empty($staffsignature), SWIFT_CRLF.$staffsignature, iif(!empty($queuesignature), SWIFT_CRLF.$queuesignature));

		// This one creates the post in database
		$ticketpostresult = $this->createTicketPost(false, POST_STAFF, 0, $staffid, $fullname, $email, $emaillist[0], $subject, $contents, false, false, false);
		$ticketpostid = $ticketpostresult[0];
		if ($_SWIFT["settings"]["t_postlist"] == 1 || $_SWIFT["settings"]["t_enhistory"] == 1)
		{
			$template->assign("postlist", $this->getTicketPosts(false, false, iif($_SWIFT["settings"]["t_cpostorder"]=="asc", "asc", "desc"), true));
		}

		// See if tgroupid is set?
		$template->setGroup(iif(empty($this->ticket["tgroupid"]), 1, $this->ticket["tgroupid"]));
		$template->loadLanguageSection("ticketemails", TEMPLATE_DB);

		$this->loadTemplateVariables();
		$template->assign("contentshtml", iif($_SWIFT["settings"]["t_chtml"]==1, nl2br(htmlspecialchars($contents)), getProcessedHTML($contents)));
		$template->assign("contentstext", $contents);
		$template->assign("ishtml", true);
		$_templateresulthtml = $template->displayTemplate("email_staffforward", TEMPLATE_DB);
		$template->assign("ishtml", false);
		$_templateresulttext = $template->displayTemplate("email_staffforward", TEMPLATE_DB);
		require_once ("./includes/functions_mail.php");
		$mailObj = new SWIFT_Mail();

		$hasattachments = $this->processPostAttachments($ticketpostid, $downloadlink, $mailObj, $_attachmentlist);

		if (_is_array($_attachmentidlist))
		{
			// Get all the attachments
			$_attachmentObj = new TicketAttachments;

			$_forwardAttachments = array();
			$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."attachments` WHERE `attachmentid` IN (". buildIN($_attachmentidlist) .");", 4);
			while ($dbCore->nextRecord(4))
			{
				if ($dbCore->Record4["ticketid"] == $this->ticket["ticketid"])
				{
//					echo "Adding Attachment: ".$dbCore->Record4["filename"]."<br>";
					$_contents = $_attachmentObj->returnAttachment($dbCore->Record4["attachmentid"], $this->ticket["ticketid"]);
					if ($_contents)
					{
						$mailObj->addAttachment($_contents, $dbCore->Record4["filename"], iif(!empty($dbCore->Record4["filetype"]), $dbCore->Record4["filetype"], 'application/octet-stream'));
					}
				}
			}
		}

		if (!empty($ticketpostresult[1]))
		{
			$messageid = sprintf('<%s@%s>', $ticketpostresult[1], $mailObj->getLocalHost());
			$mailObj->setHeader("Message-ID", $messageid);
		}

		$mailObj->setSubject($this->getEmailSubject(SUBJECT_THIRDPARTY));
		$mailObj->setData($_templateresulthtml, $_templateresulttext);

		$returnemail = $this->getReturnEmail($fromemailqueueid);
		$returnname = $this->getReturnName($fromemailqueueid);
		$mailObj->sendMail($emaillist, $returnemail, $returnname, false);

		$this->addAuditLogEntry($this->logtype, ACTION_FORWARD, sprintf($_SWIFT["language"]["al_forward"], htmlspecialchars($emailto), htmlspecialchars($_SWIFT["staff"]["fullname"])));

		return $ticketpostid;
	}

	/**
	* Resets the current status to the one in template group
	*/
	function resetTemplateGroupStatus()
	{
		global $_SWIFT;

		if ($this->ticket["ticketstatusid"] != $_SWIFT["tgroupcache"][$this->ticket["tgroupid"]]["ticketstatusid"] && !empty($this->ticket["tgroupid"]) && !empty($_SWIFT["settings"]["t_cstatusupd"]))
		{
			$this->updatesql[] = "`ticketstatusid` = '". intval($_SWIFT["tgroupcache"][$this->ticket["tgroupid"]]["ticketstatusid"]) ."'";
		}

		return true;
	}

	/**
	* Delete a ticket recipient
	*/
	function deleteRecipient($recipientid)
	{
		global $dbCore, $_SWIFT;

		$_recipient = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."ticketrecipients` AS ticketrecipients LEFT JOIN `". TABLE_PREFIX ."ticketemails` AS ticketemails ON (ticketrecipients.ticketemailid = ticketemails.ticketemailid)WHERE ticketrecipients.recipientid = '". intval($recipientid) ."';");
		if (empty($_recipient["recipientid"]) || $_recipient["ticketid"] != $this->ticket["ticketid"])
		{
			return false;
		}

		$dbCore->query("DELETE FROM `". TABLE_PREFIX ."ticketrecipients` WHERE `recipientid` = '". intval($recipientid) ."';");

		$this->addAuditLogEntry($this->logtype, ACTION_RECIPIENTDEL, sprintf($_SWIFT["language"]["al_recipientdel"], htmlspecialchars($_recipient["email"]), htmlspecialchars($_SWIFT["staff"]["fullname"])));

		return true;
	}

	/**
	* Add a Time Tracking Entry
	*/
	function addBillingEntry($billtime, $timespent, $timebillable, $forstaffid, $notes)
	{
		global $dbCore, $_SWIFT;

		if (!$this->ticket)
		{
			return false;
		}

		$this->addTimeWorked($timespent);

		$dbCore->query("INSERT INTO `". TABLE_PREFIX ."tickettimetrack` (`ticketid`, `dateline`, `creatorstaffid`, `timespent`, `timebillable`, `forstaffid`, `notes`) VALUES ('". intval($this->ticket["ticketid"]) ."', '". iif(!intval($billtime), DATENOW, intval($billtime)) ."', '". intval($_SWIFT["staff"]["staffid"]) ."', '". $dbCore->escape($timespent) ."', '". $dbCore->escape($timebillable) ."', '". intval($forstaffid) ."', '". $dbCore->escape($notes) ."');");
		$timetrackid = $dbCore->lastInsertId();

		$this->addAuditLogEntry($this->logtype, ACTION_TIMETRACK, sprintf($_SWIFT["language"]["al_timetrack"], htmlspecialchars($_SWIFT["staffcache"][$forstaffid]["fullname"]), htmlspecialchars($_SWIFT["staff"]["fullname"]), intval($timespent), intval($timebillable)));

		$this->updatesql[] = "`hasbilling` = '1'";

		return $timetrackid;
	}

	/**
	* Delete the billing entry
	*/
	function deleteBillingEntry($timetrackid)
	{
		global $dbCore, $_SWIFT;

		$_timetrack = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."tickettimetrack` WHERE `timetrackid` = '". intval($timetrackid) ."';");
		if (!empty($_timetrack))
		{
			$this->removeTimeWorked($_timetrack["timespent"]);

			$dbCore->query("DELETE FROM `". TABLE_PREFIX ."tickettimetrack` WHERE `timetrackid` = '". intval($timetrackid) ."';");

			// Recalculate Other Billing Entries
			$_hasbilling = $dbCore->queryFetch("SELECT COUNT(*) AS totalbilling FROM `". TABLE_PREFIX ."tickettimetrack` WHERE `ticketid` = '". intval($this->ticket["ticketid"]) ."';");
			$this->updatesql[] = "`hasbilling` = '". iif($_hasbilling["totalbilling"]>0, "1", "0") ."'";

			$this->addAuditLogEntry($this->logtype, ACTION_DELETETIMETRACK, sprintf($_SWIFT["language"]["al_timetrackdel"], intval($timetrackid), htmlspecialchars($_SWIFT["staff"]["fullname"])));

			require_once ("./includes/functions_customfields.php");
			deleteCustomFieldValue(CUSTOMFIELD_TIMETRACK, array($timetrackid));
		}
	}

	/**
	* Escalates the ticket, Doesnt carry out any action.. just marks it as escalated
	*/
	function escalateTicket($escalationruleid, $resetsla = false)
	{
		global $_SWIFT;

		$this->updatesql[] = "`escalationruleid` = '". intval($escalationruleid) ."'";
		$this->updatesql[] = "`isescalated` = '1'";
		$this->updatesql[] = "`escalatedtime` = '". DATENOW ."'";

		$this->resetsla = $resetsla;

		$this->addAuditLogEntry(LOG_ESCALATION, ACTION_ESCALATION, sprintf($_SWIFT["language"]["al_escalated"], $_SWIFT["escalationrulecache"][$escalationruleid]["title"]));

		$this->processTicketQueries();
	}

	/**
	* Update the Time Worked
	*/
	function updateTimeWorked($seconds)
	{
		if (!$this->ticket)
		{
			return false;
		}

		$this->updatesql[] = "`timeworked` = '".intval($seconds)."'";
	}

	/**
	* Add the Time Worked
	*/
	function addTimeWorked($minutes)
	{
		if (!$this->ticket)
		{
			return false;
		}

		$seconds = $minutes*60;
		$total = $this->ticket["timeworked"]+$seconds;
		$this->updateTimeWorked($total);
	}

	/**
	* Remove the Time Worked
	*/
	function removeTimeWorked($minutes)
	{
		if (!$this->ticket)
		{
			return false;
		}

		$seconds = $minutes*60;
		$total = $this->ticket["timeworked"]-$seconds;
		if ($total <= 0)
		{
		$total = 0;
		}
		$this->updateTimeWorked($total);
	}

	/**
	* Updates the given ticket post
	*/
	function updateTicketPost($ticketpostid, $contents)
	{
		global $dbCore, $_SWIFT;

		if (!$this->ticket)
		{
			return false;
		}

		$_ticketpost = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."ticketposts` WHERE `ticketpostid` = '". intval($ticketpostid) ."';");
		if (empty($_ticketpost["ticketpostid"]) || $_ticketpost["ticketid"] != $this->ticket["ticketid"])
		{
			return false;
		}

		$dbCore->query("UPDATE `". TABLE_PREFIX ."ticketposts` SET `edited` = '1', `editedbystaffid` = '". intval($_SWIFT["staff"]["staffid"]) ."', `editeddateline` = '". DATENOW ."', `contents` = '". $dbCore->escape($contents) ."', `contenthash` = '". $dbCore->escape(md5($contents)) ."' WHERE `ticketpostid` = '". intval($ticketpostid) ."';");

		return true;
	}

	/**
	* Gets the Ticket ID for Email Subject
	*/
	function getEmailSubjectTicketID()
	{
		global $_SWIFT;

		if ($_SWIFT["settings"]["t_eticketid"] == "seq")
		{
			return $this->ticket["ticketid"];
		} else {
			return $this->ticket["ticketmaskid"];
		}
	}

	/**
	* Gets the Email Subject
	*/
	function getEmailSubject($subjecttype, $customsubject = "", $alerttext = "")
	{
		global $_SWIFT;

		// No Queue Prefix set, itterate through queues looking for one for this department
		if (empty($this->ticket["emailqueueid"]) && count($_SWIFT["queuecache"]["list"]))
		{
			foreach ($_SWIFT["queuecache"]["list"] as $key=>$val)
			{
				if ($val["departmentid"] == $this->ticket["departmentid"])
				{
					$_emailqueueid = $val["emailqueueid"];
					break;
				}
			}
		} else {
			$_emailqueueid = $this->ticket["emailqueueid"];
		}

		$prefix = "";
		$queueprefix = $_SWIFT["queuecache"]["list"][$_emailqueueid]["prefix"];
		if (!empty($_emailqueueid) && !empty($queueprefix))
		{
			$prefix = $queueprefix." ";
		}

		if (!empty($customsubject))
		{
			$csubject = $customsubject;
		} else {
			$csubject = $this->ticket["subject"];
		}

		if ($subjecttype == SUBJECT_USER)
		{
			$subject = sprintf($_SWIFT["language"]["ticketsubjectformat"], $prefix, $this->getEmailSubjectTicketID(), $csubject);
		} else if ($subjecttype == SUBJECT_THIRDPARTY) {
			$subject = sprintf($_SWIFT["language"]["forwardticketsubjectformat"], $prefix, $this->getEmailSubjectTicketID(), $csubject);
		} else if ($subjecttype == SUBJECT_ALERT) {
			$subject = sprintf($_SWIFT["language"]["alertmailsubject"], $alerttext, $prefix, $this->getEmailSubjectTicketID(), $csubject);
		}

		return $subject;
	}

	/**
	* Return Processed Content
	*/
	function returnProcessedContent($content)
	{
		global $_SWIFT;

		if ($_SWIFT["settings"]["t_chtml"] == "entities")
		{
			return nl2br(htmlspecialchars($content));
		} else if ($_SWIFT["settings"]["t_chtml"] == "strip") {
			return getProcessedHTML(strip_tags($content));
		} else {
			return getProcessedHTML($content);
		}
	}

	/**
	* Insert a Ticket Label Link
	*/
	function insertTicketLabelLink($ticketlabelid)
	{
		global $dbCore;

		$dbCore->query("REPLACE INTO `". TABLE_PREFIX ."ticketlabellinks` (`ticketlabelid`, `ticketid`) VALUES ('". intval($ticketlabelid) ."', '". intval($this->ticket["ticketid"]) ."');");
	
		$this->updatesql[] = "`islabeled` = '1'";

		rebuildLabelCountCache();
	}

	/**
	* Delete a given Link to a label
	*/
	function deleteTicketLabelLink($ticketlabelid)
	{
		global $dbCore;

		$dbCore->query("DELETE FROM `". TABLE_PREFIX ."ticketlabellinks` WHERE `ticketlabelid` = '". intval($ticketlabelid) ."' AND `ticketid` = '". intval($this->ticket["ticketid"]) ."';");

		$_total = $dbCore->queryFetch("SELECT COUNT(*) AS totallinks FROM `". TABLE_PREFIX ."ticketlabellinks` WHERE `ticketid` = '". intval($this->ticket["ticketid"]) ."';");
		if (empty($_total["totallinks"]))
		{
			$this->updatesql[] = "`islabeled` = '0'";
		} else {
			$this->updatesql[] = "`islabeled` = '1'";
		}

		rebuildLabelCountCache();

		return true;
	}

	/**
	* Delete all given Label Links for a ticket
	*/
	function deleteAllTicketLabels()
	{
		global $dbCore;

		$dbCore->query("DELETE FROM `". TABLE_PREFIX ."ticketlabellinks` WHERE `ticketid` = '". intval($this->ticket["ticketid"]) ."';");

		$this->updatesql[] = "`islabeled` = '0'";

		rebuildLabelCountCache();

		return true;
	}

	/**
	* Loads up all the assigned labels for the ticket
	*/
	function loadTicketLabels()
	{
		global $dbCore;

		$_labelcount = 0;
		$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."ticketlabellinks` WHERE `ticketid` = '". intval($this->ticket["ticketid"]) ."';");
		while ($dbCore->nextRecord())
		{
			$this->ticket["labels"][$dbCore->Record["ticketlabellinkid"]] = $dbCore->Record;
			$_labelcount++;
		}

		if (empty($_labelcount))
		{
			$this->updatesql[] = "`islabeled` = '0'";
		}
	}

	/**
	* Assign Parser Email
	*/
	function assignParserEmail($_email)
	{
//		$this->_parseremail = $_email;
	}

	/**
	* Insert a follow up action
	*/
	function insertFollowUp($execdateline, $ownerstaffid, $departmentid, $ticketstatusid, $priorityid, $duedateline, $timeworked, $notetype, $ticketnotes, $replycontents, $forwardcontents)
	{
		global $dbCore, $_SWIFT;

		if (!$this->ticket || empty($execdateline))
		{
			return false;
		}

		$dbCore->query("INSERT INTO `". TABLE_PREFIX ."ticketfollowup` (`dateline`, `execdateline`, `ticketid`, `staffid`, `ownerstaffid`, `departmentid`, `ticketstatusid`, `priorityid`, `duedateline`, `timeworked`, `donote`, `notetype`, `ticketnotes`, `doreply`, `replycontents`, `doforward`, `forwardcontents`) VALUES ('". DATENOW ."', '". intval($execdateline) ."', '". intval($this->ticket["ticketid"]) ."', '". intval($_SWIFT["staff"]["staffid"]) ."', '". intval($ownerstaffid) ."', '". intval($departmentid) ."', '". intval($ticketstatusid) ."', '". intval($priorityid) ."', '". intval($duedateline) ."', '". intval($timeworked) ."', '". intval($notetype) ."' ,'". iif(!empty($ticketnotes), '1', '0') ."' , '". intval($notetype) ."', '". $dbCore->escape($ticketnotes) ."' ,'". iif(!empty($replycontents), '1', '0') ."' ,'". $dbCore->escape($replycontents) ."' ,'". iif(!empty($forwardcontents), '1', '0') ."', '". $dbCore->escape($forwardcontents) ."');");
		$ticketfollowupid = $dbCore->lastInsertId();

		$this->recountTicketFollowUps();

		return $ticketfollowupid;
	}

	/**
	* Delete a Follow Up
	*/
	function deleteFollowUp($ticketfollowupid)
	{
		global $dbCore, $_SWIFT;

		if (!$this->ticket || empty($ticketfollowupid))
		{
			return false;
		}

		$dbCore->query("DELETE FROM `". TABLE_PREFIX ."ticketfollowup` WHERE `ticketfollowupid` = '". intval($ticketfollowupid) ."';");

		$this->recountTicketFollowUps();

		return true;
	}

	/**
	* Recounts the follow up actions for a ticket
	*/
	function recountTicketFollowUps()
	{
		global $dbCore, $_SWIFT;

		if (!$this->ticket)
		{
			return false;
		}

		$_followupcount = $dbCore->queryFetch("SELECT COUNT(*) AS followupcount FROM `". TABLE_PREFIX ."ticketfollowup` WHERE `ticketid` = '". intval($this->ticket["ticketid"]) ."';");

		if (empty($_followupcount["followupcount"]))
		{
			$this->updatesql[] = "`followupcount` = '0'";
		} else {
			$this->updatesql[] = "`followupcount` = '". intval($_followupcount["followupcount"]) ."'";
		}
	}
}
?>